Mybatis注解开发相关
一、项目构建
1、Java项目目录结构
2、在domain包下创建User实体类
package sun.domain; import java.io.Serializable; import java.util.Date; /** * @Classname User * @Description TODO * @Date 2020/9/13 14:07 * @Created by Administrator */ public class User implements Serializable { private Integer id; private String username; private String address; private String sex; private Date birthday; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", address='" + address + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + '}'; } }
3、在dao包下创建UserDao接口
package sun.dao; 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 sun.domain.User; import javax.jws.soap.SOAPBinding; import java.util.List; /** * @Classname UserDao * @Description TODO * @Date 2020/9/13 14:09 * @Created by Administrator */ public interface UserDao { /** * 查询所有用户 */ @Select("select * from user") List<User> findAll(); /** * 根据id查user */ @Select("select * from user where id=#{id}") User findUserById(Integer id); /** * 模糊查询 */ @Select("select * from user where username like #{name}") List<User> findLike(String name); /** * 查询记录总数 */ @Select("select count(1) from user") int findTotal(); /** * 添加新用户 */ @Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})") void saveUser(User user); /** * 更新用户信息 */ @Update("update user set username=#{username},address=#{address},birthday=#{birthday},sex=#{sex} where id=#{id}") void updateUser(User user); /** * 删除用户 */ @Delete("delete from user where id=#{id}") void deleteUser(Integer id); }
4、在resource目录下创建SqlMapConfig.xml主配置文件
<?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="jdbcConfig.properties"></properties> <typeAliases> <package name="sun.domain"></package> </typeAliases> <!--配置环境--> <environments default="mysql"> <!--配置mysql环境--> <environment id="mysql"> <!--配置事务类型--> <transactionManager type="JDBC"></transactionManager> <!--配置数据库连接池--> <dataSource type="POOLED"> <!--配置连接数据库基本信息--> <property name="driver" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </dataSource> </environment> </environments> <mappers> <package name="sun.dao"></package> </mappers> </configuration>
5、创建测试类
package sun.test; import org.apache.ibatis.annotations.Select; 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 sun.dao.UserDao; import sun.domain.User; import java.io.InputStream; import java.util.List; /** * @Classname MybatisTest * @Description TODO * @Date 2020/9/13 14:57 * @Created by Administrator */ public class MybatisTest { InputStream in; SqlSessionFactoryBuilder builder; SqlSessionFactory sessionFactory; SqlSession sqlSession; UserDao userDao; @Before public void init() throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); builder = new SqlSessionFactoryBuilder(); sessionFactory = builder.build(in); sqlSession = sessionFactory.openSession(); userDao = sqlSession.getMapper(UserDao.class); } @After public void destory() throws Exception{ sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void findAllTest() throws Exception{ List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } } @Test public void findOneTest() throws Exception{ User user = userDao.findUserById(48); System.out.println(user); } @Test public void findLikeTest() throws Exception{ List<User> users = userDao.findLike("%王%"); for (User user : users) { System.out.println(user); } } @Test public void findTotalTest() throws Exception{ int total = userDao.findTotal(); System.out.println(total); } @Test public void saveUserTest() throws Exception{ User user = new User(); user.setUsername("kelvin"); user.setAddress("安徽省宿州市"); userDao.saveUser(user); } @Test public void updateTest() throws Exception{ User user = new User(); user.setId(49); user.setUsername("kelvin"); user.setAddress("安徽省宿州市"); user.setSex("男"); userDao.updateUser(user); } @Test public void deleteTest(){ userDao.deleteUser(50); } }
二、构建实体类属性和数据库表字段对应关系
在接口方法中使用@Result来构建实体类属性和数据库表字段之间的关系,后面方法如果想要使用该关系可以使用@ResultMap进行使用。
package sun.dao; import org.apache.ibatis.annotations.*; import sun.domain.User; import javax.jws.soap.SOAPBinding; import java.util.List; /** * @Classname UserDao * @Description TODO * @Date 2020/9/13 14:09 * @Created by Administrator */ public interface UserDao { /** * 查询所有用户 */ @Select("select * from user") @Results(id="userMap",value={ @Result(id=true,property = "user_id",column = "id"), @Result(property = "user_name",column = "username"), @Result(property = "user_sex",column = "sex"), @Result(property = "user_address",column = "address"), @Result(property = "user_birthday",column = "birthday"), }) List<User> findAll(); /** * 根据id查user */ @Select("select * from user where id=#{id}") // @ResultMap(value = {"userMap"}) // 正规写法 @ResultMap("userMap") // 只有一个参数 简写 User findUserById(Integer id); /** * 模糊查询 */ @Select("select * from user where username like #{name}") @ResultMap(value = {"userMap"}) List<User> findLike(String name); }
三、一对一&一对多查询
创建一对一,一对多查询主要使用了@Result中的one属性和many属性。配置one或many中的select和fetchType即可。
Java项目目录结构
1、一对一
1)在domain下创建User和Account实体类
User类:
package sun.domain; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @Classname User * @Description TODO * @Date 2020/9/13 14:07 * @Created by Administrator */ public class User implements Serializable { private Integer user_id; private String user_name; private String user_address; private String user_sex; private Date user_birthday; private List<Account> accountList; public List<Account> getAccountList() { return accountList; } public void setAccountList(List<Account> accountList) { this.accountList = accountList; } public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getUser_address() { return user_address; } public void setUser_address(String user_address) { this.user_address = user_address; } public String getUser_sex() { return user_sex; } public void setUser_sex(String user_sex) { this.user_sex = user_sex; } public Date getUser_birthday() { return user_birthday; } public void setUser_birthday(Date user_birthday) { this.user_birthday = user_birthday; } @Override public String toString() { return "User{" + "user_id=" + user_id + ", user_name='" + user_name + '\'' + ", user_address='" + user_address + '\'' + ", user_sex='" + user_sex + '\'' + ", user_birthday=" + user_birthday + '}'; } }
Account类:
package sun.domain; import java.io.Serializable; /** * @Classname Account * @Description TODO * @Date 2020/9/14 8:50 * @Created by Administrator */ public class Account implements Serializable { private Integer id; private Integer uid; private Double money; 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 + '}'; } }
2)在dao包下创建UserDao接口和AccountDao接口
UserDao接口:
package sun.dao; import org.apache.ibatis.annotations.*; import org.apache.ibatis.mapping.FetchType; import sun.domain.User; import javax.jws.soap.SOAPBinding; import java.util.List; /** * @Classname UserDao * @Description TODO * @Date 2020/9/13 14:09 * @Created by Administrator */ public interface UserDao { /** * 查询所有用户 */ @Select("select * from user") @Results(id="userMap",value={ @Result(id=true,property = "user_id",column = "id"), @Result(property = "user_name",column = "username"), @Result(property = "user_sex",column = "sex"), @Result(property = "user_address",column = "address"), @Result(property = "user_birthday",column = "birthday"), @Result(property = "accountList",column = "id", many = @Many(select = "sun.dao.AccountDao.findAccountById", fetchType = FetchType.LAZY)) }) List<User> findAll(); /** * 根据id查user */ @Select("select * from user where id=#{id}") // @ResultMap(value = {"userMap"}) // 正规写法 @ResultMap("userMap") // 只有一个参数 简写 User findUserById(Integer id); }
Account接口:
package sun.dao; 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 sun.domain.Account; import java.util.List; /** * @Classname AccountDao * @Description TODO * @Date 2020/9/14 8:52 * @Created by Administrator */ public interface AccountDao { /** * 查询所有数据 */ @Select("select * from account") //配置多对一(一对一)查询 @Results(id = "accountMap",value = { @Result(id = true,property = "id",column = "id"), @Result(property = "uid",column = "uid"), @Result(property = "money",column = "money"), @Result(property = "user",column = "uid",one = @One(select = "sun.dao.UserDao.findUserById",fetchType= FetchType.EAGER)) }) List<Account> findAll(); /** * 根据id查user */ @Select("select * from account where uid=#{id}") Account findAccountById(Integer id); }
3)创建主配置文件
4)测试
package sun.test; 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 sun.dao.AccountDao; import sun.domain.Account; import sun.domain.User; import java.io.InputStream; import java.util.List; /** * @Classname MybatisTest * @Description TODO * @Date 2020/9/13 14:57 * @Created by Administrator */ public class MybatisTest2 { InputStream in; SqlSessionFactoryBuilder builder; SqlSessionFactory sessionFactory; SqlSession sqlSession; AccountDao accountDao; @Before public void init() throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); builder = new SqlSessionFactoryBuilder(); sessionFactory = builder.build(in); sqlSession = sessionFactory.openSession(); accountDao = sqlSession.getMapper(AccountDao.class); } @After public void destory() throws Exception{ sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void findAll(){ List<Account> all = accountDao.findAll(); for (Account account : all) { System.out.println(account); System.out.println(account.getUser()); } } }
2、一对多
1)同上
2)同上
3)同上
4)测试类
package sun.test; 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 sun.dao.UserDao; import sun.domain.User; import java.io.InputStream; import java.util.List; /** * @Classname MybatisTest * @Description TODO * @Date 2020/9/13 14:57 * @Created by Administrator */ public class MybatisTest { InputStream in; SqlSessionFactoryBuilder builder; SqlSessionFactory sessionFactory; SqlSession sqlSession; UserDao userDao; @Before public void init() throws Exception { in = Resources.getResourceAsStream("SqlMapConfig.xml"); builder = new SqlSessionFactoryBuilder(); sessionFactory = builder.build(in); sqlSession = sessionFactory.openSession(); userDao = sqlSession.getMapper(UserDao.class); } @After public void destory() throws Exception { sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void findAllTest() throws Exception { List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); System.out.println(user.getAccountList()); } } }
实体类属性和表字段对应关系、一对一、一对多查询及延迟加载均在@Result注解中配置。
四、缓存配置
1、一级缓存默认开启
2、二级缓存配置
1)先在主配置文件配置
<settings> <setting name="cacheEnabled" value="true"/> </settings>
2)再在对应Dao接口上配置