使用Mybatis注解实现基本的CRUD
环境搭建
SqlMapConfig.xml的配置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33<?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="com.xushui.domain"></package>
</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>
<!--指定带有注解的dao接口所在位置-->
<mappers>
<!--配置的是dao所在位置-->
<package name="com.xushui.dao"></package>
</mappers>
</configuration>
在接口方法的上方直接写上注解,一共有四种注解@Select
、@Insert
、@Update
、Delete
1 | public interface UserMapper { |
测试代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public static void main(String[] args) throws Exception{
// 1.获取字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 2.根据字节输入流构建SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
// 3.根据SqlSessionFactory生产一个SqlSession
SqlSession sqlSession = factory.openSession();
// 4.根据SqlSession获取Dao的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 5.执行dao的方法
List<User> users = userMapper.findAll();
for (User user : users) {
System.out.println(user);
}
// 6.释放资源
sqlSession.close();
in.close();
}
需要注意的事项
如果采用了注解开发的形式就不能再在resources中对应目录下写xml,否则就会报错
Mybatis注解开发单表CRUD常用操作
示范代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52public interface UserMapper {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
void saveUser(User user);
/**
* 修改user
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where id=#{id}")
void updateUser(User user);
/**
* 根据id删除user
* @param id
*/
@Delete("delete from user where id = #{id}")
void deleteUser(Integer id);
/**
* 通过id查找用户
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
User findUserById(Integer id);
/**
* 根据用户名称模糊查询
* @param name
* @return
*/
@Select("select * from user where username like #{name}")
List<User> findUserByName(String name);
/**
* 查询用户总量
* @return
*/
@Select("select count(*) from user")
Integer findTotal();
}
多表查询(一对一)
用注解的方式解决数据库列名和对象的成员变量名不一致的问题
在Mapper中添加注解1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id = "userMap", value = {
@Result(id = true, property = "userId", column = "id"),
@Result(property = "userName", column = "username"),
@Result(property = "userBirthday", column = "birthday"),
@Result(property = "userSex", column = "sex"),
@Result(property = "userAddress", column = "address")
})
List<User> findAll();
/**
* 通过id查找用户
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
@ResultMap(value = {"userMap"})
User findUserById(Integer id);
可以通过在定义Map时给id赋值,这样子在下面就可以直接用注解@ResultMap(value = {"userMap"})
来复用,这个注解中可以添加多个map,当只有一个时,可以简写成@ResultMap("userMap")
第一步
若是一对一的关系在一个对象中添加另一个对象作为成员变量
例如:1
2
3
4
5
6
7
8
9public class Account implements Serializable {
private Integer id;
private Integer uid;
private Integer money;
// 一对一的映射
private User user;
......
}
第二步
在方法上添加注解1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public interface AccountMapper {
/**
* 查询所有账户,并且获得每个账户所属的用户信息
* @return
*/
@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"),
// property 表示要封装成什么 | column 表示用什么字段去查 | select 表示指向什么方法 | fetchType表示要选择什么方式加载(lazy延迟加载、eager立即加载)
@Result(property = "user", column = "uid", one = @One(select = "com.xushui.dao.UserMapper.findUserById",fetchType = FetchType.EAGER))
})
List<Account> findAll();
}
其中最后的@Result()
注解中
property
: 表示要封装成什么类型的数据column
: 表示要用什么字段去将你要封装的数据查询出来one
: 表示了一对一的注解select
: 表示了你要使用查询方法的全限定类名加方法名fetchType
: 取值有LAZY(延迟加载), EAGER(立即加载), DEFAULT(默认)
多表查询(一对多)
第一步
若是一对多关系则在一个对象中添加另一个对象的集合1
2
3
4
5
6
7
8
9
10
11public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
// 一对多关系映射
List<Account> accounts;
......
}
第二步
为AccountMapper添加一个方法1
2
3
4
5
6
7/**
* 根据用户id查询账户信息
* @param uid
* @return
*/
@Select("select * from account where uid = #{uid}")
List<Account> findByUid(Integer uid);
第三步
给UserMapper添加注解1
2
3
4
5
6
7
8
9
10
11
12
13
14/**
* 查询所有用户,并获取每个用户的所有账户信息
* @return
*/
@Select("select * from user")
@Results(id = "userMap", value = {
@Result(id = true, property = "userId", column = "id"),
@Result(property = "userName", column = "username"),
@Result(property = "userBirthday", column = "birthday"),
@Result(property = "userSex", column = "sex"),
@Result(property = "userAddress", column = "address"),
@Result(property = "accounts", column = "id", many = @Many(select = "com.xushui.dao.AccountMapper.findByUid", fetchType = FetchType.LAZY))
})
List<User> findAll();
关于缓存的配置
一级缓存在注解配置中是默认可以使用的
二级缓存则需要在Mapper上方添加@CacheNamespace(blocking = true)
,就可以使用了