重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
本文将介绍使用框架mybatis开发原始Dao层来对一个对数据库进行增删改查的案例。
我们提供的服务有:网站建设、成都网站设计、微信公众号开发、网站优化、网站认证、威远ssl等。为近1000家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的威远网站制作公司
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" ?>
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" ?>select LAST_INSERT_ID() insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} delete from user where id=#{id}
6、mybatis框架需要加载映射文件,将Users.xml添加在SqlMapConfig.xml,如下:
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),默认会加载该路径下的文件。希望对大家的学习有所帮助,也希望大家多多支持创新互联。