MyBatis開(kāi)發(fā)Dao層的兩種方式實(shí)現(xiàn)(原始Dao層開(kāi)發(fā))
本文將介紹使用框架mybatis開(kāi)發(fā)原始Dao層來(lái)對(duì)一個(gè)對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查的案例。
Mapper動(dòng)態(tài)代理開(kāi)發(fā)Dao層請(qǐng)閱讀我的下一篇博客:MyBatis開(kāi)發(fā)Dao層的兩種方式(Mapper動(dòng)態(tài)代理方式)
本次使用的mybatis版本為mybatis-3.2.7,開(kāi)發(fā)工具為eclipse,數(shù)據(jù)庫(kù)為mysql,jdk版本jdk1.8.0_151。
SqlSession使用范圍
SqlSessionFactoryBuilder
- 通過(guò)SqlSessionFactoryBuilder創(chuàng)建會(huì)話(huà)工廠SqlSessionFactory
- 將SqlSessionFactoryBuilder當(dāng)成一個(gè)工具類(lèi)使用即可,不需要使用單例管理SqlSessionFactoryBuilder。
- 在需要?jiǎng)?chuàng)建SqlSessionFactory時(shí)候,只需要new一次SqlSessionFactoryBuilder即可。
SqlSessionFactory
- 通過(guò)SqlSessionFactory創(chuàng)建SqlSession,使用單例模式管理sqlSessionFactory(工廠一旦創(chuàng)建,使用一個(gè)實(shí)例)。
- 將來(lái)mybatis和spring整合后,使用單例模式管理sqlSessionFactory。
SqlSession
- SqlSession是一個(gè)面向用戶(hù)(程序員)的接口。
- SqlSession中提供了很多操作數(shù)據(jù)庫(kù)的方法:如:selectOne(返回單個(gè)對(duì)象)、selectList(返回單個(gè)或多個(gè)對(duì)象)、。
- SqlSession是線(xiàn)程不安全的,在SqlSesion實(shí)現(xiàn)類(lèi)中除了有接口中的方法(操作數(shù)據(jù)庫(kù)的方法)還有數(shù)據(jù)域?qū)傩浴?/li>
- SqlSession最佳應(yīng)用場(chǎng)合在方法體內(nèi),定義成局部變量使用。
1、首先,使用eclipse新建一個(gè)java工程,在lib目錄下加入mybatis核心包、依賴(lài)包、數(shù)據(jù)驅(qū)動(dòng)包,然后BuildPath一下。。
2、添加日志文件,在classpath下創(chuàng)建log4j.properties如下:
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3、在classpath下創(chuàng)建config資源文件夾,并在config文件夾下創(chuàng)建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>
<environments default="development">
<environment id="development">
<!-- 使用jdbc事務(wù)管理-->
<transactionManager type="JDBC" />
<!-- 數(shù)據(jù)庫(kù)連接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
SqlMapConfig.xml是mybatis核心配置文件,上邊文件的配置內(nèi)容為數(shù)據(jù)源、事務(wù)管理。
4、創(chuàng)建數(shù)據(jù)封裝使用的User類(lèi)
package com.xyfer.po;
import java.util.Date;
/**
*
* @author xyfer
* 數(shù)據(jù)封裝使用的User類(lèi)
*
*/
public class User {
private int id; //id
private String username; //姓名
private String sex; //性別
private Date birthday; // 生日
private String address; // 地址
public int getId() {
return id;
}
public void setId(int id) {
this.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) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
5、在classpath下的資源文件夾sqlmapper目錄下創(chuàng)建sql映射文件User.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="test">
<!-- 根據(jù)id查詢(xún)用戶(hù) -->
<select id="findUserById" parameterType="int" resultType="com.xyfer.po.User">
select * from user where id = #{id}
</select>
<!-- 添加用戶(hù) -->
<insert id="insertUser" parameterType="com.xyfer.po.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 修改用戶(hù) -->
<update id="updateUser" parameterType="com.xyfer.po.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
where id=#{id}
</update>
<!-- 刪除用戶(hù) -->
<delete id="deleteUserById" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
6、mybatis框架需要加載映射文件,將Users.xml添加在SqlMapConfig.xml,如下:
<mappers> <mapper resource="User.xml"/> </mappers>
7、dao層接口
package com.xyfer.dao;
import com.xyfer.po.User;
public interface UserDao {
public User getUserById(int id); //根據(jù)id值查詢(xún)一個(gè)用戶(hù)
public void insertUser(User user); //新增一個(gè)用戶(hù)
public void updateUser(User user); //修改一個(gè)用戶(hù)
public void deleteUser(int id); //刪除一個(gè)用戶(hù)
}
dao層接口實(shí)現(xiàn)類(lèi)
package com.xyfer.dao.impl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.xyfer.dao.UserDao;
import com.xyfer.po.User;
public class UserDaoImpl implements UserDao {
//注入SqlSessionFactory
public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
this.setSqlSessionFactory(sqlSessionFactory);
}
private SqlSessionFactory sqlSessionFactory;
public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User getUserById(int id) {
SqlSession session = sqlSessionFactory.openSession();
User user = null;
try {
//通過(guò)sqlsession調(diào)用selectOne方法獲取一條結(jié)果集
//參數(shù)1:指定定義的statement的id,參數(shù)2:指定向statement中傳遞的參數(shù)
user = session.selectOne("test.findUserById", 1);
System.out.println(user);
} finally{
session.close();
}
return user;
}
@Override
public void insertUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.insert("test.insertUser", user);
sqlSession.commit();
} finally{
sqlSession.close();
}
}
@Override
public void updateUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.update("test.updateUser", user);
sqlSession.commit();
} finally{
sqlSession.close();
}
}
@Override
public void deleteUser(int id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.update("test.deleteUserById", id);
sqlSession.commit();
} finally{
sqlSession.close();
}
}
}
8、創(chuàng)建一個(gè)JUnit的測(cè)試類(lèi),對(duì)UserDao進(jìn)行測(cè)試。
package com.xyfer.dao.impl;
import static org.junit.Assert.*;
import java.io.InputStream;
import java.util.Date;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.xyfer.dao.UserDao;
import com.xyfer.po.User;
public class UserDaoImplTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
}
@Test
public void testGetUserById() {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user = userDao.getUserById(22);
System.out.println(user);
}
@Test
public void testInsertUser() {
User user = new User();
user.setUsername("小李");
user.setSex("男");
user.setBirthday(new Date());
user.setAddress("杭州市");
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
userDao.insertUser(user);
}
@Test
public void testUpdateUser() {
User user = new User();
user.setId(10);
user.setUsername("小威");
user.setSex("男");
user.setBirthday(new Date());
user.setAddress("杭州市");
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
userDao.updateUser(user);
}
@Test
public void testDeleteUser() {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
userDao.deleteUser(10);
}
}
以上步驟,完成使用mybatis框架開(kāi)發(fā)原始dao層,并對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查操作。
需要注意的是,上文提到的config文件夾和sqlmapper文件夾均為資源文件夾(source folder),默認(rèn)會(huì)加載該路徑下的文件。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java操作excel的三種常見(jiàn)方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Java操作excel的三種常見(jiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Java Cache詳解及簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要介紹了 Java Cache詳解及簡(jiǎn)單實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2017-02-02
springboot如何開(kāi)啟緩存@EnableCaching(使用redis)
在Spring Boot項(xiàng)目中集成Redis主要包括添加依賴(lài)到pom.xml、配置application.yml中的Redis連接參數(shù)、編寫(xiě)配置類(lèi)、在啟動(dòng)類(lèi)上添加@EnableCaching注解以及測(cè)試接口的查詢(xún)和緩存驗(yàn)證等步驟,首先,需要在pom.xml中添加spring-boot-starter-data-redis依賴(lài)2024-11-11
Javafx利用fxml變換場(chǎng)景的實(shí)現(xiàn)示例
本文主要介紹了Javafx利用fxml變換場(chǎng)景的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
Java Socket編程服務(wù)器響應(yīng)客戶(hù)端實(shí)例代碼
這篇文章主要介紹了Java Socket編程服務(wù)器響應(yīng)客戶(hù)端實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12
SpringBoot之@Controller和@RequestMapping的實(shí)現(xiàn)原理解讀
這篇文章主要介紹了SpringBoot之@Controller和@RequestMapping的實(shí)現(xiàn)原理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04

