@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
**注意:**此处我们故意和数据库表的列名不一致。
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
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 Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userBirthday=" + userBirthday +
", userSex='" + userSex + '\'' +
", userAddress='" + userAddress + '\'' +
'}';
}
}
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases>
<package name="com.atguigu.domain"/>
typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.atguigu.dao"/>
mappers>
configuration>
public interface UserDao {
/**
* 查询所有用户
*/
@Select("select * from user")
@Results(id = "userMap",
value = {
@Result(id = true, column = "id", property = "userId"),
@Result(column = "username", property = "userName"),
@Result(column = "sex", property = "userSex"),
@Result(column = "address", property = "userAddress"),
@Result(column = "birthday", property = "userBirthday")
})
List<User> findAll();
/**
* 根据id查询
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
/**
* 保存操作
*/
@Insert("insert into user(username,sex,birthday,address)values(#{userName},#{userSex},#{userBirthday},#{userAddress})")
@SelectKey(keyColumn = "id", keyProperty = "userId", resultType = Integer.class, before =
false, statement = {"select last_insert_id()"})
int saveUser(User user);
/**
* 更新操作
*/
@Update("update user set username=#{userName},address=#{userAddress},sex=#{userSex},birthday=#{userBirthday} where id =#{userId} ")
int updateUser(User user);
/**
* 删除用户
*/
@Delete("delete from user where id = #{userId} ")
int deleteUser(Integer userId);
/**
* 查询使用聚合函数
*/
@Select("select count(*) from user ")
int findTotal();
/**
* 模糊查询
*/
@Select("select * from user where username like #{userName} ")
@ResultMap("userMap")
List<User> findByName(String name);
}
public class Test1 {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private UserDao userDao;
@Before//junit的注解
public void init() throws Exception {
//1.读取配置文件
in = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
factory = builder.build(in);
//3.创建 session
session = factory.openSession();
//4.创建代理对象
userDao = session.getMapper(UserDao.class);
}
@After//junit 的注解
public void destroy() throws Exception {
//提交事务
session.commit();
//释放资源
session.close();
//关闭流
in.close();
}
@Test
public void test() {
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test2() {
User user = userDao.findById(46);
System.out.println(user);
}
@Test
public void test3() {
User user = new User();
user.setUserName("尹会东");
user.setUserSex("男");
user.setUserAddress("黑龙江");
user.setUserBirthday(new Date());
userDao.saveUser(user);
System.out.println(user.getUserId());
}
@Test
public void test4() {
User user = new User();
user.setUserName("尹会东");
user.setUserSex("男");
user.setUserAddress("大庆");
user.setUserBirthday(new Date());
user.setUserId(51);
userDao.updateUser(user);
}
@Test
public void test5() {
userDao.deleteUser(51);
}
@Test
public void test6() {
System.out.println(userDao.findTotal());
}
@Test
public void test7() {
List<User> users = userDao.findByName("%尹%");
for (User user : users) {
System.out.println(user);
}
}
}
实现复杂关系映射之前我们可以在映射文件中通过配置来实现,在使用注解开发时我们需要借助@Results 注解,@Result 注解,@One 注解,@Many 注解。
@Results 注解
代替的是标签
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或 @Results(@Result())
@Result 注解
代替了 标签和标签
@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=""))
需求:
加载账户信息时并且加载该账户的用户信息,根据情况可实现延迟加载。(注解方式实现)
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//多对一关系映射:从表方应该包含一个主表方的对象引用
private 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;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
", user=" + user +
'}';
}
}
/**
* 查询账户信息
*/
@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 = "com.atguigu.dao.UserDao.findById",
fetchType = FetchType.LAZY))
})
List<Account> findAll();
@Test
public void test(){
List<Account> all = accountDao.findAll();
for (Account a:all){
System.out.println(a);
}
}
需求:
查询用户信息时,也要查询他的账户列表。使用注解方式实现。
分析:
一个用户具有多个账户信息,所以形成了用户(User)与账户(Account)之间的一对多关系。
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
List<Account> accounts;
@Select("select * from user")
@Results(id = "userMap",
value = {
@Result(id = true, column = "id", property = "userId"),
@Result(column = "username", property = "userName"),
@Result(column = "sex", property = "userSex"),
@Result(column = "address", property = "userAddress"),
@Result(column = "birthday", property = "userBirthday"),
@Result(column = "id", property = "accounts",
many = @Many(
select = "com.atguigu.dao.AccountDao.findById",
fetchType = FetchType.LAZY
)
)
})
List<User> findAll();
/**
* 根据id查询
*/
@Select("select * from account where uid=#{uid}")
Account findById(Integer id);
@Test
public void test() {
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
}
<settings>
<setting name="cacheEnabled" value="true"/>
settings>
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {
}
Mybatis后续的学习:
mybatis 概述 | 配置文件详解:https://blog.csdn.net/weixin_45606067/article/details/107368570
mybatis 事务 | 动态SQL | 多表查询:https://blog.csdn.net/weixin_45606067/article/details/107368642
mybatis延迟加载 | 缓存机制详解:https://blog.csdn.net/weixin_45606067/article/details/107368706
mybatis 逆向工程的使用:https://blog.csdn.net/weixin_45606067/article/details/107368781
pageHelper分页技术:https://blog.csdn.net/weixin_45606067/article/details/107368847