亲宝软件园·资讯

展开

MyBatis开发Dao层 MyBatis开发Dao层的两种方式实现(原始Dao层开发)

谢亚峰 人气:0

本文将介绍使用框架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),默认会加载该路径下的文件。希望对大家的学习有所帮助,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论