The statement

This blog is based on the relevant dark horse programmers of the course summary, interested in can go to see the video tutorial, no nonsense, or more recommended. This blog is actually a summary of the previous Mybatis, with the more commonly used method in the form of ———— annotations.

The planned content of this blog is:

  1. Multiple table query operations
  2. Configuration of cache

Database preparation

Create two tables in the same library:

DROP TABLE IF EXISTS `user`; CREATE TABLE 'user' (' id 'int(11) NOT NULL AUTO_increment,' username 'varchar(32) NOT NULL COMMENT' user ', 'birthday' datetime default NULL COMMENT 'birthday ',' sex 'char(1) default NULL COMMENT' sex ', 'address' varchar(256) default NULL COMMENT 'address ', PRIMARY KEY (' id')) ENGINE=InnoDB default CHARSET=utf8; Insert into 'user' (' id ',' username ',' sex ',' address ') values (41,' birthday ','2018-02-27 ' 17:47:08 'and' male 'and' Beijing '), (42, 'king of small 2', '2018-03-02 15:09:37', 'female' and 'Beijing Jin Yanlong'), (43, 'king of small 2', '2018-03-04 Jin Yanlong 11:34:34 'and' female 'and' Beijing '), (45 'preach wisdom podcasts,' the 2018-03-04 12:04:06 'and' male ', 'Beijing Jin Yanlong'), (46, 'Lao wang', '2018-03-07 17:37:26 'and' male 'and' Beijing '), (48, 'ma Po li', '2018-03-08 11:44:00', 'female' and 'Beijing correction'); DROP TABLE IF EXISTS `account`; CREATE TABLE 'account' (' ID 'int(11) NOT NULL COMMENT' ID ', 'UID' int(11) default NULL COMMENT 'ID ', 'MONEY' double default NULL COMMENT 'value ', PRIMARY KEY (' ID'), KEY 'FK_Reference_8' (' UID '), CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Insert into ` account ` (` ID `, ` UID `, ` MONEY `) values (1,41,1000),,45,1000 (2), (3,41,2000);Copy the code

Environment set up

Create a New Maven project. Overall, it’s not much different from the last post.

Changes to IUserDao:

package com.zhouman.dao; import com.zhouman.domain.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; Public interface IUserDao {@return */ @select (" Select * from user") List< user > findAll(); /** * Select(" Select * from user where ID = #{id}") user findById(Integer) userId); /** * Select(" Select * from user where username like #{username}") List<User> findByName(String username); }Copy the code

User changes:

package com.zhouman.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private Integer userId; private String userName; private String userAddress; private String userSex; private Date userBirthday; @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", userAddress='" + userAddress + '\'' + ", userSex='" + userSex + '\'' + ", userBirthday=" + userBirthday + '}'; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; }}Copy the code

AnnotationCRUDTest changes

package com.zhouman.test; import com.zhouman.dao.IUserDao; import com.zhouman.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; public class AnnotationCRUDTest { private InputStream inputStream; private SqlSessionFactory sessionFactory; private SqlSession sqlSession; private IUserDao userDao; @Before public void init() throws IOException { //1. Get byte input stream inputStream = Resources. GetResourceAsStream (" SqlMapConfig. XML "); SessionFactory = new SqlSessionFactoryBuilder().build(inputStream); / / 3. According to the production a SqlSession SqlSessionFactory SqlSession = sessionFactory. OpenSession (); UserDao = sqlsession.getMapper (iUserDao.class); //4. } @After public void destroy() throws IOException { //6. SqlSession.com MIT (); sqlSession.close(); inputStream.close(); } @Test public void testFindAll(){ List<User> users = userDao.findAll(); for(User user : users){ System.out.println(user); } } @Test public void testFindById(){ System.out.println(userDao.findById(57)); System.out.println(userDao.findById(58)); } @test public void testFindByName(){List<User> users = userdao.findByName ("% king %"); for (User user : users){ System.out.println(user); }}}Copy the code

How to establish the correspondence between entity class attributes and database column names

AnnotationCRUDTest (); findAll ();

It was found that the User query result could be encapsulated, but none of the attributes except username were displayed.

This is because the attribute names of our User class are different from the column names of the tables in the database.

So why is userName displayed? This is because Mybatis is case insensitive. So username is the same as username.

Previously, the DAO interface. XML method can be processed using resultMap tags.

What about annotation development?

First, a possible but not recommended method: aliasing SQL statements.

The recommended practice is to use mybatis@Resultsannotation

Use @results in front of the corresponding method body in the IUserDao interface:

@results (value = {@result (id = true,column = "id", column = "id", property = "userId"), @Result(column = "username", property = "userName"), @Result(column = "address", property = "userAddress"), @Result(column = "sex", property = "userSex"), @Result(column = "birthday", property = "userBirthday"), }) List<User> findAll();Copy the code

Execution Result:

However, there is a drawback to the above approach, which is that other methods have to rewrite the corresponding annotation if there is a problem, such as findById, which is very cumbersome and ugly.

Improvement methods:

package com.zhouman.dao; import com.zhouman.domain.User; import org.apache.ibatis.annotations.*; import java.util.List; Public interface IUserDao {@return */ @select (" Select * from user") @results (id = "userMap", value = { @Result(id = true,column = "id", property = "userId"), @Result(column = "username", property = "userName"), @Result(column = "address", property = "userAddress"), @Result(column = "sex", property = "userSex"), @Result(column = "birthday", property = "userBirthday"), }) List<User> findAll(); @param userId * @return */ @select (" Select * from user where ID = #{id}") @resultMap ("userMap") user findById(Integer userId); /** * Select(" Select * from user where username like #{username}") @ResultMap("userMap") List<User> findByName(String username); }Copy the code

I’m not going to put the results up, take up space.

Annotation developing a one-to-one query configuration for multi-table queries

Create an Account entity class under the Domain package

package com.zhouman.domain; import java.io.Serializable; public class Account implements Serializable { private Integer id; private Integer uid; private Double money; // Many-to-one mapping private User User; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", uid=" + uid + ", money=" + money + '}'; }}Copy the code

Create the IAccountDao interface under the DAO package

package com.zhouman.dao; import com.zhouman.domain.Account; import org.apache.ibatis.annotations.One; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.mapping.FetchType; import java.util.List; Public interface IAccountDao {/** * Query all accounts. * @return */ @select (" Select * from account") @results (id = "accountMap",value = {@result (id = true, column = "id", property = "id"), @Result(column = "uid", property = "uid"), @Result(column = "money", property = "money"), @Result(property = "user", column = "uid", one = @One(select = "com.zhouman.dao.IUserDao.findById",fetchType = FetchType.EAGER)) }) List<Account> findAll(); }Copy the code

Create a new test class to test

package com.zhouman.test; import com.zhouman.dao.IAccountDao; import com.zhouman.dao.IUserDao; import com.zhouman.domain.Account; import com.zhouman.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class AccountTest { private InputStream inputStream; private SqlSessionFactory sessionFactory; private SqlSession sqlSession; private IAccountDao accountDao; @Before public void init() throws IOException { //1. Get byte input stream inputStream = Resources. GetResourceAsStream (" SqlMapConfig. XML "); SessionFactory = new SqlSessionFactoryBuilder().build(inputStream); / / 3. According to the production a SqlSession SqlSessionFactory SqlSession = sessionFactory. OpenSession (); //4. Use SqlSession to obtain the Dao proxy object accountDao = SQLSession.getMapper (iAccountDao.class); } @After public void destroy() throws IOException { //6. SqlSession.com MIT (); sqlSession.close(); inputStream.close(); } @Test public void testFindAll(){ List<Account> accounts = accountDao.findAll(); for(Account account : accounts){ System.out.println("------------------------"); System.out.println(account); System.out.println(account.getUser()); }}}Copy the code

Query result:

Annotations develop a one – to – many query configuration for multi-table queries

For example, one user corresponds to multiple accounts

Add the following to the User entity class under the domain package:

Private List<Account> accounts; private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; }Copy the code

Add a method to the IAccountDao interface:

@param userId * @return */ @select (" Select * from account where uid = #{userId}") findAccountByUid(Integer userId);Copy the code

Improved comments in findAll method in IUserDao interface:

@return */ @select (" Select * from user") @results (id = "userMap", value = { @Result(id = true,column = "id", property = "userId"), @Result(column = "username", property = "userName"), @Result(column = "address", property = "userAddress"), @Result(column = "sex", property = "userSex"), @Result(column = "birthday", property = "userBirthday"), @Result(property = "accounts", column = "id", many = @Many(select = "com.zhouman.dao.IAccountDao.findAccountByUid", fetchType = FetchType.LAZY)) }) List<User> findAll();Copy the code

To test the class that executes the findAll method

The result is:

The results are split because the comment in the previous step: fetchType = fetchType.LAZY enables LAZY loading

Use level 2 caching for annotation development

Tired, this part of the content will not learn!