您好,登錄后才能下訂單哦!
本文將介紹使用框架mybatis開發原始Dao層來對一個對數據庫進行增刪改查的案例。
Mapper動態代理開發Dao層請閱讀我的下一篇博客:MyBatis開發Dao層的兩種方式(Mapper動態代理方式)
本次使用的mybatis版本為mybatis-3.2.7,開發工具為eclipse,數據庫為mysql,jdk版本jdk1.8.0_151。
SqlSession使用范圍
SqlSessionFactoryBuilder
SqlSessionFactory
SqlSession
1、首先,使用eclipse新建一個java工程,在lib目錄下加入mybatis核心包、依賴包、數據驅動包,然后BuildPath一下。。
2、添加日志文件,在classpath下創建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下創建config資源文件夾,并在config文件夾下創建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事務管理--> <transactionManager type="JDBC" /> <!-- 數據庫連接池--> <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核心配置文件,上邊文件的配置內容為數據源、事務管理。
4、創建數據封裝使用的User類
package com.xyfer.po; import java.util.Date; /** * * @author xyfer * 數據封裝使用的User類 * */ 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目錄下創建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"> <!-- 根據id查詢用戶 --> <select id="findUserById" parameterType="int" resultType="com.xyfer.po.User"> select * from user where id = #{id} </select> <!-- 添加用戶 --> <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> <!-- 修改用戶 --> <update id="updateUser" parameterType="com.xyfer.po.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> <!-- 刪除用戶 --> <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); //根據id值查詢一個用戶 public void insertUser(User user); //新增一個用戶 public void updateUser(User user); //修改一個用戶 public void deleteUser(int id); //刪除一個用戶 }
dao層接口實現類
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 { //通過sqlsession調用selectOne方法獲取一條結果集 //參數1:指定定義的statement的id,參數2:指定向statement中傳遞的參數 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、創建一個JUnit的測試類,對UserDao進行測試。
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框架開發原始dao層,并對數據庫進行增刪改查操作。
需要注意的是,上文提到的config文件夾和sqlmapper文件夾均為資源文件夾(source folder),默認會加載該路徑下的文件。希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。