最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Mybatis原始dao开发方式

互联网 admin 0浏览 0评论

Mybatis原始dao开发方式

1、准备一个pojo类

User.java

package com.gxa.pojo;import java.util.Date;public class User {private Long id;private String username;private String password;private String salt;private String phone;private Date created;private Date lastLoginTime;private Integer status;public User(Long id, String username, String password, String salt, String phone, Date created, Date lastLoginTime, Integer status) {this.id = id;this.username = username;this.password = password;this.salt = salt;this.phone = phone;this.created = created;this.lastLoginTime = lastLoginTime;this.status = status;}public User() {}/*** @return id*/public Long getId() {return id;}/*** @param id*/public void setId(Long id) {this.id = id;}/*** @return username*/public String getUsername() {return username;}/*** @param username*/public void setUsername(String username) {this.username = username;}/*** @return password*/public String getPassword() {return password;}/*** @param password*/public void setPassword(String password) {this.password = password;}/*** @return salt*/public String getSalt() {return salt;}/*** @param salt*/public void setSalt(String salt) {this.salt = salt;}/*** @return phone*/public String getPhone() {return phone;}/*** @param phone*/public void setPhone(String phone) {this.phone = phone;}/*** @return created*/public Date getCreated() {return created;}/*** @param created*/public void setCreated(Date created) {this.created = created;}/*** @return last_login_time*/public Date getLastLoginTime() {return lastLoginTime;}/*** @param lastLoginTime*/public void setLastLoginTime(Date lastLoginTime) {this.lastLoginTime = lastLoginTime;}/*** @return status*/public Integer getStatus() {return status;}/*** @param status*/public void setStatus(Integer status) {this.status = status;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", salt='" + salt + '\'' +", phone='" + phone + '\'' +", created=" + created +", lastLoginTime=" + lastLoginTime +", status=" + status +'}';}
}

2、准备一个工具类,封装SqlSessionFactory

MyBatisUtils.java
package com.gxa.utils;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 java.io.IOException;
import java.io.InputStream;public class MyBatisUtils {//确保一次请求只有一个sqlSession对象private static ThreadLocal<SqlSession> t1 = new ThreadLocal<SqlSession>();private static SqlSessionFactory sqlSessionFactory;static {try {//1、创建sqlSessionFactoryBuilder对象SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//2、加载mybatis主配置文件InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");//3、加载配置文件创建SqlSession工厂sqlSessionFactory = sqlSessionFactoryBuilder.build(in);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("加载主配置文件失败!");}}/*** 获取当去线程的SqlSession** @return*/public static SqlSession getSqlSession() {//1、先从当前线程获取SqlSessionSqlSession sqlSession = t1.get();//2、如果有直接返回,如果没有则创建一个新的SqlSession,放入当前线程,再返回if (sqlSession == null) {//创建一个SqlSessionsqlSession = sqlSessionFactory.openSession();//将sqlSession绑定到当前线程t1.set(sqlSession);}return sqlSession;}/*** 提交事务*/public static void commitTransaction() {SqlSession sqlSession = t1.get();//对SqlSession进行判断,如果sqlSession存在,则提交if (sqlSession != null) {sqlSession.commit();}}/*** 关闭sqlSession,且从当前线程移除*/public static void closeSqlSession() {SqlSession sqlSession = t1.get();if (sqlSession != null) {sqlSession.close();t1.remove();}}
}

3、准备一个接口

注意:Mapper.xml中的sql标签的id应该与接口中的方法名保持一致

UserDao.java

package com.gxa.dao;import com.gxa.pojo.User;import java.util.List;public interface UserDao {public User queryUserById(Long id);public List<User> queryAll();public List<User> queryUserByUsername(String username);public void insertUser(User user);public void updateUser(User user);public void deleteUserById(Long id);
}

4、接口的实现类

UserDaoImpl.java

package com.gxa.dao.impl;import com.gxa.dao.UserDao;
import com.gxa.pojo.User;
import com.gxa.utils.MyBatisUtils;import java.util.List;public class UserDaoImpl implements UserDao {@Overridepublic User queryUserById(Long id) {return MyBatisUtils.getSqlSession().selectOne("queryUserById", id);}@Overridepublic List<User> queryAll() {return MyBatisUtils.getSqlSession().selectList("queryAll");}@Overridepublic List<User> queryUserByUsername(String username) {return MyBatisUtils.getSqlSession().selectList("queryUserByUsername", username);}@Overridepublic void insertUser(User user) {MyBatisUtils.getSqlSession().insert("insertUser", user);MyBatisUtils.commitTransaction();}@Overridepublic void updateUser(User user) {MyBatisUtils.getSqlSession().insert("updateUser", user);MyBatisUtils.commitTransaction();}@Overridepublic void deleteUserById(Long id) {MyBatisUtils.getSqlSession().delete("deleteUserById", id);MyBatisUtils.commitTransaction();}
}

5、sql映射文件

User.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"".dtd">
<!-- 命名空间,用于隔离sql,后面还有一个很重要的作用 -->
<mapper namespace="test"><!--    查询数据--><select id="queryUserById" parameterType="long" resultType="com.gxa.pojo.User">select * from user where id = #{id}</select><!--    查询全部的用户信息--><select id="queryAll" resultType="com.gxa.pojo.User">select * from user</select><select id="queryUserByUsername" parameterType="string" resultType="com.gxa.pojo.User">select * from user where username like '%${value}%'</select><!--    插入数据--><insert id="insertUser" parameterType="com.gxa.pojo.User" useGeneratedKeys="true" keyProperty="id">insert into user(username,password,salt,phone,created,last_login_time,status)values(#{username},#{password},#{salt},#{phone},#{created},#{lastLoginTime},#{status})</insert><!--    修改用户--><update id="updateUser" parameterType="com.gxa.pojo.User">update user set username = #{username},password = #{password} where id = #{id}</update><!--    删除用户--><delete id="deleteUserById" parameterType="long">delete from user where id = #{id}</delete></mapper>

6、测试类

package com.gxa.test;import com.gxa.dao.UserDao;
import com.gxa.dao.impl.UserDaoImpl;
import com.gxa.pojo.User;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestUserDao {private UserDao userDao = new UserDaoImpl();@Testpublic void testQueryAll() {List<User> users = userDao.queryAll();System.out.println(users);}@Testpublic void testQueryUserById() {User user = userDao.queryUserById(1L);System.out.println(user);}@Testpublic void testQueryUserByUsername() {List<User> users = userDao.queryUserByUsername("优");System.out.println(users);}@Testpublic void testInsertUser() {User user = new User(null, "哈哈哈", "123123", "xxxx", "qqqqq", new Date(), new Date(), 1);userDao.insertUser(user);}@Testpublic void testUpdateUser() {User user = new User(7L, "hahaha", "123123", "xxxx", "qqqqq", new Date(), new Date(), 1);userDao.updateUser(user);}@Testpublic void testDeleteUserById() {userDao.deleteUserById(7L);}}

 

Mybatis原始dao开发方式

1、准备一个pojo类

User.java

package com.gxa.pojo;import java.util.Date;public class User {private Long id;private String username;private String password;private String salt;private String phone;private Date created;private Date lastLoginTime;private Integer status;public User(Long id, String username, String password, String salt, String phone, Date created, Date lastLoginTime, Integer status) {this.id = id;this.username = username;this.password = password;this.salt = salt;this.phone = phone;this.created = created;this.lastLoginTime = lastLoginTime;this.status = status;}public User() {}/*** @return id*/public Long getId() {return id;}/*** @param id*/public void setId(Long id) {this.id = id;}/*** @return username*/public String getUsername() {return username;}/*** @param username*/public void setUsername(String username) {this.username = username;}/*** @return password*/public String getPassword() {return password;}/*** @param password*/public void setPassword(String password) {this.password = password;}/*** @return salt*/public String getSalt() {return salt;}/*** @param salt*/public void setSalt(String salt) {this.salt = salt;}/*** @return phone*/public String getPhone() {return phone;}/*** @param phone*/public void setPhone(String phone) {this.phone = phone;}/*** @return created*/public Date getCreated() {return created;}/*** @param created*/public void setCreated(Date created) {this.created = created;}/*** @return last_login_time*/public Date getLastLoginTime() {return lastLoginTime;}/*** @param lastLoginTime*/public void setLastLoginTime(Date lastLoginTime) {this.lastLoginTime = lastLoginTime;}/*** @return status*/public Integer getStatus() {return status;}/*** @param status*/public void setStatus(Integer status) {this.status = status;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", salt='" + salt + '\'' +", phone='" + phone + '\'' +", created=" + created +", lastLoginTime=" + lastLoginTime +", status=" + status +'}';}
}

2、准备一个工具类,封装SqlSessionFactory

MyBatisUtils.java
package com.gxa.utils;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 java.io.IOException;
import java.io.InputStream;public class MyBatisUtils {//确保一次请求只有一个sqlSession对象private static ThreadLocal<SqlSession> t1 = new ThreadLocal<SqlSession>();private static SqlSessionFactory sqlSessionFactory;static {try {//1、创建sqlSessionFactoryBuilder对象SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//2、加载mybatis主配置文件InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");//3、加载配置文件创建SqlSession工厂sqlSessionFactory = sqlSessionFactoryBuilder.build(in);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("加载主配置文件失败!");}}/*** 获取当去线程的SqlSession** @return*/public static SqlSession getSqlSession() {//1、先从当前线程获取SqlSessionSqlSession sqlSession = t1.get();//2、如果有直接返回,如果没有则创建一个新的SqlSession,放入当前线程,再返回if (sqlSession == null) {//创建一个SqlSessionsqlSession = sqlSessionFactory.openSession();//将sqlSession绑定到当前线程t1.set(sqlSession);}return sqlSession;}/*** 提交事务*/public static void commitTransaction() {SqlSession sqlSession = t1.get();//对SqlSession进行判断,如果sqlSession存在,则提交if (sqlSession != null) {sqlSession.commit();}}/*** 关闭sqlSession,且从当前线程移除*/public static void closeSqlSession() {SqlSession sqlSession = t1.get();if (sqlSession != null) {sqlSession.close();t1.remove();}}
}

3、准备一个接口

注意:Mapper.xml中的sql标签的id应该与接口中的方法名保持一致

UserDao.java

package com.gxa.dao;import com.gxa.pojo.User;import java.util.List;public interface UserDao {public User queryUserById(Long id);public List<User> queryAll();public List<User> queryUserByUsername(String username);public void insertUser(User user);public void updateUser(User user);public void deleteUserById(Long id);
}

4、接口的实现类

UserDaoImpl.java

package com.gxa.dao.impl;import com.gxa.dao.UserDao;
import com.gxa.pojo.User;
import com.gxa.utils.MyBatisUtils;import java.util.List;public class UserDaoImpl implements UserDao {@Overridepublic User queryUserById(Long id) {return MyBatisUtils.getSqlSession().selectOne("queryUserById", id);}@Overridepublic List<User> queryAll() {return MyBatisUtils.getSqlSession().selectList("queryAll");}@Overridepublic List<User> queryUserByUsername(String username) {return MyBatisUtils.getSqlSession().selectList("queryUserByUsername", username);}@Overridepublic void insertUser(User user) {MyBatisUtils.getSqlSession().insert("insertUser", user);MyBatisUtils.commitTransaction();}@Overridepublic void updateUser(User user) {MyBatisUtils.getSqlSession().insert("updateUser", user);MyBatisUtils.commitTransaction();}@Overridepublic void deleteUserById(Long id) {MyBatisUtils.getSqlSession().delete("deleteUserById", id);MyBatisUtils.commitTransaction();}
}

5、sql映射文件

User.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"".dtd">
<!-- 命名空间,用于隔离sql,后面还有一个很重要的作用 -->
<mapper namespace="test"><!--    查询数据--><select id="queryUserById" parameterType="long" resultType="com.gxa.pojo.User">select * from user where id = #{id}</select><!--    查询全部的用户信息--><select id="queryAll" resultType="com.gxa.pojo.User">select * from user</select><select id="queryUserByUsername" parameterType="string" resultType="com.gxa.pojo.User">select * from user where username like '%${value}%'</select><!--    插入数据--><insert id="insertUser" parameterType="com.gxa.pojo.User" useGeneratedKeys="true" keyProperty="id">insert into user(username,password,salt,phone,created,last_login_time,status)values(#{username},#{password},#{salt},#{phone},#{created},#{lastLoginTime},#{status})</insert><!--    修改用户--><update id="updateUser" parameterType="com.gxa.pojo.User">update user set username = #{username},password = #{password} where id = #{id}</update><!--    删除用户--><delete id="deleteUserById" parameterType="long">delete from user where id = #{id}</delete></mapper>

6、测试类

package com.gxa.test;import com.gxa.dao.UserDao;
import com.gxa.dao.impl.UserDaoImpl;
import com.gxa.pojo.User;
import org.junit.Test;import java.util.Date;
import java.util.List;public class TestUserDao {private UserDao userDao = new UserDaoImpl();@Testpublic void testQueryAll() {List<User> users = userDao.queryAll();System.out.println(users);}@Testpublic void testQueryUserById() {User user = userDao.queryUserById(1L);System.out.println(user);}@Testpublic void testQueryUserByUsername() {List<User> users = userDao.queryUserByUsername("优");System.out.println(users);}@Testpublic void testInsertUser() {User user = new User(null, "哈哈哈", "123123", "xxxx", "qqqqq", new Date(), new Date(), 1);userDao.insertUser(user);}@Testpublic void testUpdateUser() {User user = new User(7L, "hahaha", "123123", "xxxx", "qqqqq", new Date(), new Date(), 1);userDao.updateUser(user);}@Testpublic void testDeleteUserById() {userDao.deleteUserById(7L);}}

 

11136

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论