1 常用注解
2 使用注解实现基本crud
2. 1 基本目录结构
2.2 添加依赖 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>untitled2</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
<!--在build中配置resources,防止maven资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2.3 添加核心配置文件 sqlconfig.xml
注意 普通xml mapper 映射的是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>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/book?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com\lize\dao"/>
<!-- <package name="com/lize/dao/IUserDao.xml"/>-->
</mappers>
</configuration>
2.4 编写实体类
IuserDao
package com.keafmd.domain;
import java.io.Serializable;
import java.util.Date;
/**
* Keafmd
*
* @ClassName: User
* @Description: User实体类
* @author: lize
* @date: 2021-02-16 20:28
*/
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 +
'}';
}
}
2.5编写持久化接口
package com.keafmd.dao;
import com.keafmd.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;
/**
* Keafmd
*
* @ClassName: IUserDao
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-02-16 20:30
*/
/**
* 在mybatis中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer userId);
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
//@Select("select * from user where username like #{username}") //占位符
@Select("select * from user where username like '%${value}%'") //字符串拼接
List<User> findByName(String username);
/**
* 查询总数量
* @return
*/
@Select("select count(*) from user")
int findTotal();
}
3 基于注解实现复杂的sql数据
实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现, 在使用注解开发时我们需要借助@Results 注解,@Result 注解,@One 注解,@Many 注解。
1 各种注解解释
@Results 注解
代替的是标签<resultMap>
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或@Results(@Result())
@Resutl 注解
代替了<id> 标签和<result>标签
@Result 中的属性介绍:
@One 注解(一对一)
代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One 注解属性介绍:
select 指定用来多表查询的 sqlmapper
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。
使用格式:@Result(column=" “,property=”",one=@One(select=""))
@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.keafmd.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();
@Many 注解(多对一)
代替了<collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义。
使用格式:@Result(property="",column="",many=@Many(select=""))
4 基于注解的缓存
4.1 1级缓存
@Test
public void testFindOne(){
User user = userDao.findById(55);
System.out.println(user);
User user2 = userDao.findById(55);
System.out.println(user2);
System.out.println(user==user2);
}
```结果
```java
2021-02-17 03:26:22,736 164 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-02-17 03:26:22,970 398 [ main] DEBUG source.pooled.PooledDataSource - Created connection 85445963.
2021-02-17 03:26:22,971 399 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:26:22,975 403 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Preparing: select * from user where id=?
2021-02-17 03:26:23,001 429 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Parameters: 55(Integer)
2021-02-17 03:26:23,054 482 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <== Total: 1
2021-02-17 03:26:23,055 483 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:26:23,055 483 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 55(Integer)
2021-02-17 03:26:23,056 484 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
true
2021-02-17 03:26:23,056 484 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:26:23,056 484 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:26:23,057 485 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 85445963 to pool.
Process finished with exit code 0
5.2 2级缓存
1 早中心配置文件中开启
<!--配置开启二级缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
2 在持久层配置 @CacheNameSpace
package com.keafmd.dao;
import com.keafmd.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
/**
* Keafmd
*
* @ClassName: IUserDao
* @Description:
* @author: 牛哄哄的柯南
* @date: 2021-02-16 20:30
*/
/**
* 在mybatis中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
@CacheNamespace(blocking = true) //mybatis 基于注解方式实现配置二级缓存 *这里*
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id = true,column = "id",property = "userId"),
@Result(column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts" ,column = "id",
many = @Many(select = "com.keafmd.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
//@ResultMap(value={"userMap"})
@ResultMap("userMap")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username}") //占位符
@ResultMap("userMap")
List<User> findByName(String username);
}