1.结构图
2.实体类User(解决属性名和数据库字段名不匹配)
package com.itheima.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer Id;
private String userName;
private String Sex;
private String addRess;
private Date birThday;
/*一个用户有多个账户:一对多*/
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getAddRess() {
return addRess;
}
public void setAddRess(String addRess) {
this.addRess = addRess;
}
public Date getBirThday() {
return birThday;
}
public void setBirThday(Date birThday) {
this.birThday = birThday;
}
@Override
public String toString() {
return "User{" +
"Id=" + Id +
", userName='" + userName + '\'' +
", Sex='" + Sex + '\'' +
", addRess='" + addRess + '\'' +
", birThday=" + birThday +
'}';
}
}
3.实体类Account
package com.itheima.pojo;
import java.io.Serializable;
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 +
'}';
}
}
4.实体类接口IUserDao
package com.itheima.dao;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
//开启二级缓存
@CacheNamespace(blocking = true)
public interface IUserDao {
//查询所有
//id就是让其他的来一起使用:唯一标识
@Select(value = "select * from user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "Id"),
@Result(column = "username",property = "userName"),
@Result(column = "sex",property = "Sex"),
@Result(column = "address",property = "addRess"),
@Result(column = "birthday",property = "birThday"),
@Result(property = "accounts",column = "id" ,
many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
fetchType= FetchType.LAZY))
})
List<User> findUser();
//查询根据id
@Select("select * from user where id = #{id}")
//@ResultMap("userMap")//可以使用多个map,这里是只有一个
@ResultMap(value = {"userMap"})//标准写法
User findById(Integer id);
//模糊查询
@Select("select * from user where username like #{username}")
@ResultMap(value = {"userMap"})//标准写法
List<User> findByName(String username);
}
5.实体类接口AccountDao
package com.itheima.dao;
import com.itheima.pojo.Account;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
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(property = "user",column = "uid",one = @One(select="com.itheima.dao.IUserDao.findById",fetchType = FetchType.EAGER))
}
)
List<Account> findAll();
/*
* 根据用户id查询账户信息
* */
@Select("select * from account where uid = #{Id}")
List<Account> findAccountByUid(Integer userId);
}
6.外部数据库jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456
7.主配置文件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>
<!--p配置外部数据库-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置开启二级缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<!--配置别名-->
<typeAliases>
<!--自定义别名 实体类所在位置-->
<package name="com.itheima.pojo"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--指定带有接口注解的位置-->
<mappers>
<package name="com.itheima.dao"/>
</mappers>
</configuration>
8.测试类TestAccountCRUD(测试一对多)
package com.itheima;
import com.itheima.dao.IAccountDao;
import com.itheima.dao.IUserDao;
import com.itheima.pojo.Account;
import com.itheima.pojo.User;
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 java.io.InputStream;
import java.util.List;
public class TestAccountCRUD {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IAccountDao accountDao;
//初始化
@Before
public void init() throws Exception {
//1.获取字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据字节输入流构建SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.根据SqlSessionFactory生产一个SqlSession
sqlSession = factory.openSession();
//4.使用SqlSession获取Dao的代理对象
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After
public void destroy() throws Exception{
//6.释放资源..
sqlSession.commit();
sqlSession.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());
}
}
}
9.测试类TestCRUD(多对多)
package com.itheima;
import com.itheima.dao.IUserDao;
import com.itheima.pojo.User;
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 java.io.InputStream;
import java.util.Date;
import java.util.List;
public class TestCRUD {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IUserDao userDao;
//初始化
@Before
public void init() throws Exception {
//1.获取字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据字节输入流构建SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.根据SqlSessionFactory生产一个SqlSession
sqlSession = factory.openSession();
//4.使用SqlSession获取Dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy() throws Exception{
//6.释放资源..
sqlSession.commit();
sqlSession.close();
in.close();
}
//查询所有
@Test
public void testFindAll(){
/*查询用户下的账户信息*/
List<User> users = userDao.findUser();
for (User user:users){
System.out.println("查询用户信息--------------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
//查询一个
@Test
public void testFindOne(){
User user = userDao.findById(8);
System.out.println("查询成功---"+user);
}
//模糊查询
@Test
public void testFindName(){
/*多条数据用list*/
List<User> users = userDao.findByName("%王%");
for (User user:users){
System.out.println("模糊查询成功---"+user);
}
}
}
10.测试类(一级缓存和二级缓存)
package com.itheima;
import com.itheima.dao.IUserDao;
import com.itheima.pojo.User;
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 java.io.InputStream;
import java.util.List;
public class TestSecondLevelCache {
private InputStream in;
private SqlSessionFactory factory;
//初始化
@Before
public void init() throws Exception {
//1.获取字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据字节输入流构建SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
}
@After
public void destroy() throws Exception{
//6.释放资源
in.close();
}
//查询一个
@Test
public void testFindOne(){
SqlSession session1 = factory.openSession();
IUserDao userDao1 = session1.getMapper(IUserDao.class);
User user1 = userDao1.findById(7);
System.out.println(user1);
session1.close();//释放一级缓存
SqlSession session2 = factory.openSession();
IUserDao userDao2 = session2.getMapper(IUserDao.class);
User user2 = userDao2.findById(7);
System.out.println(user2);
session2.close();//使用二级缓存
}
}
11.依赖pom.xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
总结:各有各的好处:注解和配置文件都差不多,用熟悉一种最好(加油小伙伴)