一、使用 Mybatis 對數據庫 User 表一對一查詢
第一步:封裝對數據庫表的映射 User.java
package cn.lemon.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
第二步:新建持久層(dao)接口 IUserDao.java ,操作數據庫
package cn.lemon.dao;
import cn.lemon.domain.User;
import java.util.List;
public interface IUserDao {
int update(User user);
User findById(Integer userId);
List<User> findAll(User user);
}
第三步:新建配置文件 SqlMapConfig.xml 和 jdbc.properties
<?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">
<!--mybatis 配置文件-->
<configuration>
<!--使用 屬性文件 jdbc.properties-->
<properties resource="jdbc.properties"></properties>
<!--定義別名-->
<typeAliases>
<!--定義單個別名-->
<!--<typeAlias type="cn.lemon.domain.User" alias="user"></typeAlias>-->
<!--配置包定義別名-->
<package name="cn.lemon.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.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!--配置映射文件-->
<mappers>
<!--配置包的映射文件-->
<package name="cn.lemon.dao"></package>
</mappers>
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///db_mybatis?serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=lemon
第四步:編寫持久層接口的映射文件 IUserDao.xml (注意文件路徑)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lemon.dao.IUserDao">
<!--定義Sql片段-->
<sql id="defaultSql">
select * from user
</sql>
<update id="update" parameterType="user">
update user
<set>
<if test="username != null and username.trim() != ''">
username = #{username},
</if>
<if test="birthday != null">
birthday = #{birthday},
</if>
<if test="sex != null and sex.trim() != ''">
sex = #{sex},
</if>
<if test="address != null and address.trim() != ''">
address = #{address}
</if>
</set>
where id = #{id};
</update>
<select id="findById" parameterType="int" resultType="user">
/*導入定義Sql片段*/
<include refid="defaultSql"></include>
where id = #{id}
</select>
<select id="findAll" resultType="user" parameterType="user">
<include refid="defaultSql"></include>
<where>
<if test="username != null and username.trim() !=''">
and username like '%${username}%'
</if>
<if test="birthday != null and birthday.trim() !=''">
and birthday like '%${birthday}%'
</if>
<if test="sex != null and sex.trim() !=''">
and sex like '%${sex}%'
</if>
<if test="address != null and address.trim() !=''">
and address like '%${address}%'
</if>
</where>
</select>
</mapper>
第五步:拷貝日誌文件 log4j.properties,這樣我們就可以在控制檯看到打印日誌
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
#log4j.rootCategory=debug, CONSOLE, LOGFILE
log4j.rootCategory=debug, CONSOLE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
#log4j.appender.LOGFILE=org.apache.log4j.FileAppender
#log4j.appender.LOGFILE.File=d:\axis.log
#log4j.appender.LOGFILE.Append=true
#log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
第六步:測試類
package cn.lemon.dao;
import cn.lemon.domain.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.text.SimpleDateFormat;
import java.util.List;
public class IUserDaoTest {
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private IUserDao iUserDao;
private SimpleDateFormat simpleDateFormat;
@Before
public void init() throws Exception {
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");//以流的形式獲取配置文件
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//產生mybatis 工廠類
sqlSession = sqlSessionFactory.openSession(true);//得到session ,true 表示打開自動提交事務
iUserDao = sqlSession.getMapper(IUserDao.class);//得到mybatis 的mapper代理對象
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//String轉date
}
@After
public void destroy() throws Exception {
//關閉資源
sqlSession.close();
inputStream.close();
}
@Test
public void update() throws Exception{
User user = new User();
user.setId(64);
user.setUsername("章澤天");
user.setBirthday(simpleDateFormat.parse("2017-1-12 10:10:10"));
user.setSex("女");
user.setAddress("北京");
iUserDao.update(user);
}
@Test
public void findById() {
User user = iUserDao.findById(64);
System.out.println(user);
}
@Test
public void findAll() {
User user = new User();
user.setUsername("李");
user.setSex("男");
user.setAddress("北京");
List<User> userList = iUserDao.findAll(user);
for (User u : userList) {
System.out.println(u);
}
}
}
二、一對多
第一步:新建映射賬戶表的實體類 Account.java,記得寫上記錄關聯關係的屬性
package cn.lemon.domain;
public class Account {
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(外鍵)對應User表中的id=" + uid +
", money=" + money +
'}';
}
}
第二步:新建持久層接口 IAccountDao.java
package cn.lemon.dao;
import cn.lemon.domain.Account;
import java.util.List;
public interface IAccountDao {
List<Account> findAll();//查詢所有賬號
}
第三步:新建映射文件 IAccountDao.xml(配置是重點)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lemon.dao.IAccountDao">
<!--配置查詢所有-->
<select id="findAll" resultMap="accountMapLemon">
<!--使用顯式內連接查詢(或隱式內連接)-->
select u.*, a.id as aid, a.uid, a.money from account a inner join user u on a.uid = u.id;
<!--select u.*, a.id as aid, a.uid, a.money from account a, user u where a.uid = u.id-->
</select>
<!--resultMap 處理映射,建立表與表的對應關係-->
<resultMap id="accountMapLemon" type="account">
<id property="id" column="aid"/><!--property:屬性,column:列名-->
<result property="uid" column="uid"/>
<result property="money" column="money"/>
<!--
association : 映射從表方
映射多對一,多的一方的實體屬性
-->
<association property="user" javaType="user">
<id property="id" column="id"/><!--主鍵不能省略-->
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
</association>
</resultMap>
</mapper>
第四步:測試類
package cn.lemon.dao;
import cn.lemon.domain.Account;
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;
import static org.junit.Assert.*;
public class IAccountDaoTest {
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private IAccountDao iAccountDao;
@Before
public void init() throws Exception {
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
iAccountDao = sqlSession.getMapper(IAccountDao.class);
}
@Test
public void findAll() {
List<Account> accountList = iAccountDao.findAll();
for (Account account : accountList) {
System.out.println(account);
System.out.println(account.getUser());
System.out.println("------------------------------");
}
}
@After
public void destroy() throws Exception {
//關閉資源
sqlSession.close();
inputStream.close();
}
}
三、多對一
第一步:在實體類 User.java 中添加 Account 屬性,並生成 get 和 set 方法
private List<Account> accountList = new ArrayList<>();
第二步:修改映射文件 IUserDao.xml 中的 findAll 方法
<!--配置查詢所有-->
<select id="findAll2" resultMap="userMapLemon">
select u.*, a.id as aid, a.uid, a.money from account a inner join user u on a.uid = u.id;
</select>
<!--resultMap 處理映射,建立表與表之間的對應關係-->
<resultMap id="userMapLemon" type="user">
<id column="id" property="id"/><!--column:列明 property:屬性-->
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!--
collection 是用於建立一對多中集合屬性的對應關係
ofType 用於指定集合元素的數據類型,可以寫別名
collection 部分定義了用戶關聯的賬戶信息。表示關聯查詢結果集,映射一對多中一的一方(也就是主表方)
property="accList":關聯查詢的結果集存儲在 User 對象的上哪個屬性。
ofType="account":指定關聯查詢的結果集中的對象類型即List中的對象類型。此處可以使用別名,也可以使用全限定名。
-->
<collection property="accountList" ofType="Account">
<id column="aid" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
</collection>
</resultMap>
第三步:測試類中添加方法
@Test
public void findAll2(){
List<User> userList = iUserDao.findAll2();
for (User user : userList) {
System.out.println(user);
System.out.println(user.getAccountList());
System.out.println("----------------------------");
}
}
四、多對多
user 表與 role 表之間是多對多
查詢角色我們需要用到 role 表,但角色分配的用戶的信息我們並不能直接找到用戶信息,而是要通過中間表( user_role 表)才能關聯到用戶信息。SQL語句爲:(顯式內聯)
SELECT
r.*, u.id uid,
u.username username,
u.birthday birthday,
u.sex sex,
u.address address
FROM
role r
INNER JOIN
user_role ur
ON ( r.id = ur.rid)
INNER JOIN
user u
ON (ur.uid = u.id);
第一步:新建實體類 Role.java
package cn.lemon.domain;
import java.util.ArrayList;
import java.util.List;
public class Role {
private Integer roleId;
private String roleName;
private String roleDesc;
private List<User> userList = new ArrayList<>();
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
第二步:持久層新建查詢所有角色 IRoleDao.java 接口
package cn.lemon.dao;
import cn.lemon.domain.Role;
import java.util.List;
public interface IRoleDao {
List<Role> findAll();//查詢所有角色
}
第三步:映射文件 IRoleDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lemon.dao.IRoleDao">
<select id="findAll" resultMap="roleMapLemon">
SELECT r.*, u.id uid, u.username username, u.birthday birthday, u.sex sex, u.address address FROM role r INNER JOIN user_role ur ON ( r.id = ur.rid) INNER JOIN user u ON (ur.uid = u.id);
</select>
<!--resultMap 處理映射,建立表與表的對應關係-->
<resultMap id="roleMapLemon" type="role">
<id property="roleId" column="id"/>
<result property="roleName" column="role_name"/>
<result property="roleDesc" column="role_desc"/>
<!--映射集合-->
<collection property="userList" ofType="user">
<id property="id" column="uid"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
</collection>
</resultMap>
</mapper>
第四步:測試類
package cn.lemon.dao;
import cn.lemon.domain.Role;
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 IRoleDaoTest {
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private IRoleDao iRoleDao;
@Before
public void init() throws Exception {
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
iRoleDao = sqlSession.getMapper(IRoleDao.class);
}
@Test
public void findAll() {
List<Role> roleList = iRoleDao.findAll();
for (Role role : roleList) {
System.out.println(role);
System.out.println(role.getUserList());
System.out.println("------------------------");
}
}
@After
public void destroy() throws Exception {
sqlSession.close();
inputStream.close();
}
}
代碼下載請 點擊