Mybatis注解
Mybatis不仅可以使用XML文件的形式配置信息,更为方便的方式是使用注解。注解省去了反复的XML文件中的标签配置,大大的提高了开发效率。
1. 单表操作
我们依然以前面的user为例来说明如何使用注解来实现单表的增删改查,此时user的信息为:
mysql> select * from user;
+----+----------+---------------------+------+---------+
| id | username | birthday | sex | address |
+----+----------+---------------------+------+---------+
| 41 | Forlogen | 2018-02-27 17:47:08 | 男 | Beijing |
| 42 | Kobe | 2018-03-02 15:09:37 | 男 | LA |
| 43 | James | 2018-03-04 11:34:34 | 男 | USA |
+----+----------+---------------------+------+---------+
3 rows in set (0.00 sec)
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>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
<typeAliases>
<package name="domain"/>
</typeAliases>
<environments default="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>
<mapper class="dao.IUserDao"/>
</mappers>
</configuration>
Mybatis提供了如下的注解来实现常用的数据库操作:
- @Insert:实现新增
- @Update:实现更新
- @Delete:实现删除
- @Select:实现查询
- @Result:实现结果集封装
- @Results:可以与@Result一起使用,封装多个结果集
- @ResultMap:实现引用
- @Results定义的封装
- @One:实现一对一结果集封装
- @Many:实现一对多结果集封装
- @SelectProvider: 实现动态SQL映射
- @CacheNamespace:实现注解二级缓存的使用
然后在IUserDao中添加方法,实现user表的CURD操作。由于这里使用的是注解的形式,因此我们不必再写接口对应的xml文件,也不应该写,否则测试方法将出错。
1.1 查找
public interface IUserDao {
@Select("select * from user")
List<User> findAll();
}
public class UserTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll(){
List<User> all = userDao.findAll();
for (User user : all) {
System.out.println(user);
}
}
执行单元测试,输出如下所示,可见它和直接使用SQL语句执行的结果是相同的。
User{id=41, username='Forlogen', address='Beijing', sex='男', birthday=Wed Feb 28 01:47:08 CST 2018}
User{id=42, username='Kobe', address='LA', sex='男', birthday=Fri Mar 02 23:09:37 CST 2018}
User{id=43, username='James', address='USA', sex='男', birthday=Sun Mar 04 19:34:34 CST 2018}
1.2 插入
public interface IUserDao {
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
}
@Test
public void testSaveUser(){
User user = new User();
user.setUsername("Ball");
user.setAddress("Shanghai");
user.setSex("女");
userDao.saveUser(user);
}
执行单元测试后再去数据库表中看一下是否插入成功,从查询结果中可以看出插入是成功的。
mysql> select * from user;
+----+----------+---------------------+------+----------+
| id | username | birthday | sex | address |
+----+----------+---------------------+------+----------+
| 41 | Forlogen | 2018-02-27 17:47:08 | 男 | Beijing |
| 42 | Kobe | 2018-03-02 15:09:37 | 男 | LA |
| 43 | James | 2018-03-04 11:34:34 | 男 | USA |
| 47 | Ball | NULL | 女 | Shanghai |
+----+----------+---------------------+------+----------+
4 rows in set (0.00 sec)
1.3 更新
public interface IUserDao {
@Update("update user set username=#{username} where id=#{id}")
void updateUser(User user);
}
@Test
public void testUpdateUser(){
User user = new User();
user.setUsername("Amy");
user.setId(46);
userDao.updateUser(user);
}
执行单元测试后再去查看表信息,如下所示,可见更新操作执行成功。
mysql> select * from user;
+----+----------+---------------------+------+----------+
| id | username | birthday | sex | address |
+----+----------+---------------------+------+----------+
| 41 | Forlogen | 2018-02-27 17:47:08 | 男 | Beijing |
| 42 | Kobe | 2018-03-02 15:09:37 | 男 | LA |
| 43 | James | 2018-03-04 11:34:34 | 男 | USA |
| 47 | Amy | NULL | 女 | Shanghai |
+----+----------+---------------------+------+----------+
4 rows in set (0.00 sec)
1.4 删除
public interface IUserDao {
@Delete("delete from user where id=#{id}")
void deleteUser(Integer id);
}
@Test
public void testDeleteUser(){
userDao.deleteUser(45);
}
执行删除操作再查看数据库表信息,发现删除成功。
mysql> select * from user;
+----+----------+---------------------+------+---------+
| id | username | birthday | sex | address |
+----+----------+---------------------+------+---------+
| 41 | Forlogen | 2018-02-27 17:47:08 | 男 | Beijing |
| 42 | Kobe | 2018-03-02 15:09:37 | 男 | LA |
| 43 | James | 2018-03-04 11:34:34 | 男 | USA |
+----+----------+---------------------+------+---------+
3 rows in set (0.00 sec)
1.5 条件查询
public interface IUserDao {
@Select("select * from user where id=#{id}")
User findById(Integer id);
}
@Test
public void testFindById(){
User user = userDao.findById(41);
System.out.println(user);
}
执行单元测试,输出为:
User{id=41, username='Forlogen', address='Beijing', sex='男', birthday=Wed Feb 28 01:47:08 CST 2018}
1.6 统计查询
public interface IUserDao {
@Select("select count(*) from user")
int findTotal();
}
@Test
public void testFindTotal(){
int total = userDao.findTotal();
System.out.println(total);
}
执行单元测试,输出:
3
2. 联合查询
@Results注解 代替的是标签 该注解中可以使用单个@Result注解,也可以使用@Result集合
@Results({@Result(),@Result()})或 @Results(@Result())
@Resutl注解 代替了 标签和标签 @Result 中 属性介绍:
- id 是否是主键字段
- column 数据库的列名
- property需要装配的属性名
- one 需要使用的@One注解(@Result(one=@One)()))
- many 需要使用的@Many注解(@Result(many=@many)()))
@One注解(一对一) 代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One注解属性介绍:
-
select 指定用来多表查询的sqlmapper
-
fetchType会覆盖全局的配置参数lazyLoadingEnabled
-
使用格式:
@Result(column=" ",property="",one=@One(select=""))
@Many注解(多对一) 代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。 注意:聚集元素用来处理“一对多”的关系。需要指定映射的Java实体类的属性,属性的javaType(一般为ArrayList)但是注注解中可以不定义; 使用格式:
@Result(property="",column="",many=@Many(select=""))
2.1 一对一映射查询
加载账户信息时并且加载该账户的用户信息。首先编写user和account表对应的实体类,然后编写持久层接口:
public interface IAccountDao {
@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(column = "uid", property = "user", one=@One(select = "dao.IUserDao.findById", fetchType = FetchType.EAGER))
})
List<Account> findAll();
}
public interface IUserDao {
@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 = "dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
@Select("select * from user where id=#{id} ")
@ResultMap("userMap")
User findById(Integer userId);
}
最后编写测试方法,执行单元测试。
public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IAccountDao accountDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
accountDao = session.getMapper(IAccountDao.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.close();
in.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());
}
}
}
2.2 一对多映射查询
一个用户可能又多个账户,查询用户信息时,也要查询对应的账户信息。
public interface IUserDao {
@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 = "dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
}
public interface IAccountDao {
@Select("select * from account where uid = #{userId}")
List<Account> findAccountByUid(Integer userId);
}
编写测试方法,执行单元测试:
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for(User user : users){
System.out.println("---------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
转载:https://blog.csdn.net/Forlogen/article/details/106924407