MyBatis Annotation Development

Keywords: Mybatis JDBC Database xml

Article directory

1. Entity class

Create entity classes corresponding to database tables.

  • Cake
public class Cake {
    private Long id;
    private Long categoryId;
    private String name;
    private Integer level;
    private Integer price;     // Price, integer, divided into unit storage
    private byte[] smallImg;   // Pictures (binary data)
    private Date createTime;
    private Date updateTime;
    
    // set and get methods for attributes
    ...
}
  • Category
public class Category {
    private Long id;
    private String name;
    private Date createTime;
    private Date updateTime;

    // set and get methods for attributes
    ...
}

2. Configuration file

  • MyBatis root profile
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!-- package Configure the interface under this package to automatically inject persistence operations -->
        <package name="com.moc.cake_mall.mapper"/>
    </mappers>
</configuration>
  • jdbc source configuration
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/cake?useUnicode=true&characterEncoding=UTF-8
username=root
password=root

3. Persistent Mapping Interface

  • CakeMapper
public interface CakeMapper {
    // Paging query
    @Select("select * from cake order by create_time desc limit #{skip}, #{size}")
    // @ Result annotation =="This annotation is a way to match table fields with entity attributes
    @Results({
                // id = true denotes that the field is the primary key
                @Result(id = true, column = "id", property = "id"),
                @Result(column = "category_id", property = "categoryId"),
                @Result(column = "name", property = "name"),
                @Result(column = "level", property = "level"),
                @Result(column = "price", property = "price"),
                @Result(column = "create_time", property = "createTime"),
                @Result(column = "update_time", property = "updateTime")
            })
    List<Cake> getCakes(Integer skip, Integer size);


    // Paging queries based on Classification
    @Select("select id, category_id categoryId, name, level, price, " + 
            "create_time createTime, update_time updateTime" + 
            "from cake where category_id = #{categoryId}" + 
            "order by create_time desc limit #{skip}, #{size}")
    // @ Param annotation== gives the parameter a name. After the parameter is named, the parameter value {categoryId} can be obtained according to the name.
    // Annotation is required for each value that needs to be passed in to the SQL statement
    List<Cake> getCakesByCategoryId(@Param("categoryId") Long categoryId, @Param("skip") Integer skip, @Param("size") Integer size);


    // Number statistics based on classification ID
    @Select("select count(*) from cake where category_id = #{categoryId}")
    int countCakesByCategoryId(@Param("categoryId") Long categoryId);

    
    // Save information
    // Cake in cake.xxx can be omitted when there is only one parameter
    @Insert("insert into cake(category_id, name, level, " + 
            "price, small_img, create_time, update_time) " +
            "value (#{cake.categoryId}, #{cake.name}, " + 
            "#{cake.level}, #{cake.price}, #{cake.smallImg}, " +
            "#{cake.createTime}, #{cake.updateTime})")
    void addCake(@Param("cake") Cake cake);

    
    // Inquire about cake picture information
    // select * from table name for update: Lock the queried data and no one else can query for updates
    @Select("select small_img smallImg from cake where id = #{id} for update")
    Cake getImg(@Param("id") Long id);
}
  • CategoryMapper
public interface CategoryMapper {
    // Query all
    // @ Select annotation== queries the database, using aliases to match entity class attributes if there are aliases
    @Select("select id, name, create_time createTime, update_time updateTime from category")
    List<Category> getCategories();


    // Delete a specific item according to ID
    // @ Delete annotation =="database deletion operation, #{id} is consistent with the parameter ID name, from which the value is obtained
    @Delete("delete from category where id = #{id}")
    void deleteById(Long id);


    // Insert cake classification information
    // @ Insert Annotation== Adding rows to the database to take values from attributes of parameter objects
    @Insert("insert into category(name, create_time, update_time)" +
            "values(#{name}, #{createTime}, #{updateTime}")
    void addCategory(Category category);
}

4. MyBatis Tool Class

It is mainly used to obtain SQLSession instances.

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            String resource = "config.xml";
            reader = Resources.getResourceAsReader(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
}

5. Service Class

Implement more specific business operations for specific persistent interface classes.

  • CakeService
public class CakeService {
    // Search for merchandise information based on classification ID (paginated content)
    public List<Cake> getCakesByCategoryId(Long categoryId, Integer page, Integer size) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            return mapper.getCakesByCategoryId(categoryId, (page - 1) * size, size);
        } finally {
            sqlSession.close();
        }
    }

    // Adding Business Data Operations
    public void addCake(Cake cake) {
        Date now = new Date();
        cake.setCreateTime(now);
        cake.setUpdateTime(now);
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            mapper.addCake(cake);
            sqlSession.commit();  // Note that you need to submit here
        } finally {
            sqlSession.close();
        }
    }

    // Specified business query operation
    public int countCakesByCategoryId(Long categoryId) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            return mapper.countCakesByCategoryId(categoryId);
        } finally {
            sqlSession.close();
        }
    }

    // Specified business query operation
    public Cake getCakeImg(Long id) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            return mapper.getImg(id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return null;
    }
}
  • CategoryService
public class CategoryService {
    // Specified business query operation
    public List<Category> getCategories() {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CategoryMapper mapper = sqlSession.getMapper(CategoryMapper.class);
            return mapper.getCategories();
        } finally {
            sqlSession.close();
        }
    }

    // Adding Business Data Operations
    public void addCategory(Category category) {
        Date now = new Date();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CategoryMapper mapper = sqlSession.getMapper(CategoryMapper.class);
            mapper.addCategory(category);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}

6. Application Layer

This is where persistence operations are used in servlets.

public class CakeServlet extends HttpServlet {
    private CakeService cakeService;
    private CategoryService categoryService;

    @Override
    public void init() throws ServletException {
        super.init();
        cakeService = new CakeService();
        categoryService = new CategoryService();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		...
		List<Cake> cakes = cakeService.getCakesByCategoryId(categoryId, 1, 5000);
		List<Category> categories = categoryService.getCategories();
		cakeService.addCake(cake);
		categoryService.addCategory(category);
		int count = cakeService.countCakesByCategoryId(categoryId);
		Cake cake = cakeService.getCakeImg(Long.valueOf(idStr));
		...
    }

    @Override
    public void destroy() {
        super.destroy();
        cakeService = null;
        categoryService = null;
    }
}

Posted by g.grillo on Thu, 04 Apr 2019 19:48:30 -0700