之前我自己写的BookCool项目持久层(DAO层)用的是JDBCTemplate操作的,现在改成mybatis了
1.新建一个web项目(BookCool)
2.创建一个数据库BookCool然后在该数据库用户表创建users表
这里我将用户账号uaccount设成唯一键了,后面我基本上都是使用uaccount字段来操作users表
3.创建实体包codewen.bookcool.entity并在其中创建用户实体类User,实现可序列化接口(mybatis中有二级缓存,二级缓存会将查询的信息从内存写入到硬盘,需要实现可序列化接口),数据类型都用包装类(数据库字段默认值一般都为null,基本数据类型不能为空,而包装类可以)
import java.io.Serializable;
/**
* 用户实体类
* @author codewen
*
*/
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private Integer uid;//用户编号
private String uaccount;//用户账号
private String upwd;//用户密码
private String usex;//性别
private Integer uage;//年龄
private String uemail;//邮箱
private String utel;//电话
private String uaddress;//住址
private String uintroduction;//用户介绍
private String role;//用户级别(默认为普通用户)
private String uregistTime;//用户注册时间
public User() {
}
public User(String uaccount, String upwd, String role) {
this.uaccount = uaccount;
this.upwd = upwd;
this.role = role;
}
public User(String uaccount, String upwd, String usex, Integer uage,
String uemail, String utel, String uaddress, String uintroduction) {
this.uaccount = uaccount;
this.upwd = upwd;
this.usex = usex;
this.uage = uage;
this.uemail = uemail;
this.utel = utel;
this.uaddress = uaddress;
this.uintroduction = uintroduction;
}
public User(String uaccount, String upwd, String usex, Integer uage,
String uemail, String utel, String uaddress, String uintroduction,
String role) {
this.uaccount = uaccount;
this.upwd = upwd;
this.usex = usex;
this.uage = uage;
this.uemail = uemail;
this.utel = utel;
this.uaddress = uaddress;
this.uintroduction = uintroduction;
this.role = role;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUaccount() {
return uaccount;
}
public void setUaccount(String uaccount) {
this.uaccount = uaccount;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
public Integer getUage() {
return uage;
}
public void setUage(Integer uage) {
this.uage = uage;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUtel() {
return utel;
}
public void setUtel(String utel) {
this.utel = utel;
}
public String getUaddress() {
return uaddress;
}
public void setUaddress(String uaddress) {
this.uaddress = uaddress;
}
public String getUintroduction() {
return uintroduction;
}
public void setUintroduction(String uintroduction) {
this.uintroduction = uintroduction;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getUregistTime() {
return uregistTime;
}
public void setUregistTime(String uregistTime) {
this.uregistTime = uregistTime;
}
@Override
public String toString() {
return "User [uid=" + uid + ", uaccount=" + uaccount + ", upwd=" + upwd
+ ", usex=" + usex + ", uage=" + uage + ", uemail=" + uemail
+ ", utel=" + utel + ", uaddress=" + uaddress
+ ", uintroduction=" + uintroduction + ", role=" + role
+ ", uregistTime=" + uregistTime + "]";
}
}
4.新建一个与src同级的源文件夹conf,用于存放配置文件以及mapper文件
复制三个jar到lib文件夹(log4j是日志jar,mybatis是mybatisjar,mysql-connector-java是mysql驱动jar)并全部add to build Path,另外,下jar包,建议到maven仓库中去搜
如:
在conf文件夹下新建一个db.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/bookcool
mysql.username=root
mysql.password=123
在conf文件夹下新建一个log4j.properties
###设置Logger输出级别和输出目的地(stdout控制台输出)
log4j.rootLogger=debug,stdout
###把日志信息输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
###log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%p] %m%n
在src文件夹下新建持久层接口包codewen.bookcool.mapper,并在其中新建一个UserMapper接口(接口中暂时写一些简单的CRUD方法,之后需要再加)
import java.util.List;
import codewen.bookcool.entity.User;
/**
* 用户持久层操作接口类
* @author codewen
*
*/
public interface UserMapper {
//增加用户方法
public boolean addUser(User user);
// 删除用户的方法 通过uaccount来删除
public boolean deleteUser(String uaccount);
// 修改用户信息的方法 通过user来修改用户信息
public boolean updateUser(User user);
// 通过uaccount查询该用户
public User queryUser(String uaccount);
//查询所有用户
public List<User> queryUsers();
}
在conf文件夹下也新建一个codewen.bookcool.mapper包,该包用于放mapper文件,并在其中创建一个UserMapper.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="codewen.bookcool.mapper.UserMapper">
<!-- //增加用户方法
public boolean addUser(User user); -->
<insert id="addUser" parameterType="codewen.bookcool.entity.User">
insert into users(uaccount,upwd,usex,uage,uemail,utel,uaddress,uintroduction)
values(#{uaccount},#{upwd},#{usex},#{uage},#{uemail},#{utel},#{uaddress},#{uintroduction})
</insert>
<!-- // 删除用户的方法 通过uaccount来删除
public boolean deleteUser(String uaccount); -->
<delete id="deleteUser" parameterType="String">
delete from users where uaccount=#{uaccount}
</delete>
<!-- // 修改用户信息的方法 通过user来修改用户信息
public boolean updateUser(User user); -->
<update id="updateUser" parameterType="codewen.bookcool.entity.User">
update users
<set>
<if test="upwd!=null and upwd!=''">
upwd=#{upwd},
</if>
<if test="usex!=null and usex!=''">
usex=#{usex},
</if>
<if test="uage!=null and uage>0">
uage=#{uage},
</if>
<if test="uemail!=null and uemail!=''">
uemail=#{uemail},
</if>
<if test="utel!=null and utel!=''">
utel=#{utel},
</if>
<if test="uaddress!=null and uaddress!=''">
uaddress=#{uaddress},
</if>
<if test="uintroduction!=null and uintroduction!=''">
uintroduction=#{uintroduction}
</if>
</set>
<where>
uaccount=#{uaccount}
</where>
</update>
<!-- // 通过uaccount查询该用户
public User queryUser(String uaccount); -->
<select id="queryUser" parameterType="String" resultType="codewen.bookcool.entity.User">
select * from users where uaccount=#{uaccount}
</select>
<!-- //查询所有用户
public List<User> queryUsers(); -->
<select id="queryUsers" resultType="codewen.bookcool.entity.User">
select * from users
</select>
</mapper>
在conf文件夹下新建conf.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>
<!-- 加载外部的配置文件 -->
<properties resource="db.properties"/>
<!-- 设置重要参数 -->
<settings>
<!-- 开启驼峰命名规则 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 配置log4j -->
<setting name="logImpl" value="LOG4J"/>
<!-- 开启懒加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启属性懒加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 注册单个mapper文件 -->
<mapper resource="codewen/bookcool/mapper/UserMapper.xml"/>
</mappers>
</configuration>
在src文件夹下新建两个包codewen.bookcool.util和codewen.bookcool.test
在util包中创建一个Mybatis工具类
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* mybatis工具类
* @author codewen
*
*/
public class MyBatisUtil {
private static SqlSessionFactory sessionFactory = null;
//使用本地线程管理sqlsession,保证了线程安全
private static ThreadLocal<SqlSession> sessionThread = new ThreadLocal<SqlSession>();
//静态代码块初始化sessionFactory
static {
try {
InputStream is = Resources.getResourceAsStream("conf.xml");
sessionFactory = new SqlSessionFactoryBuilder().build(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//获取sessionFactory
public static SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
//新建session,将session放入本地线程中
private static void newSession() {
SqlSession session = sessionFactory.openSession();
sessionThread.set(session);
}
//获取session
public static SqlSession getSession() {
SqlSession session = sessionThread.get();
if(session == null) {
//调用newSession(),新建session,将session放入本地线程中
newSession();
//从本地线程中获取session
session = sessionThread.get();
}
return session;
}
//关闭session
public static void closeSession() {
SqlSession session = sessionThread.get();
if(session != null) {
//关闭session
session.close();
//将本地线程的SqlSession设为null
sessionThread.set(null);
}
}
}
接下来在test包中新建一个UserTest测试类,测试增删改查操作有没有问题
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import codewen.bookcool.entity.User;
import codewen.bookcool.mapper.UserMapper;
import codewen.bookcool.until.MyBatisUtil;
import codewen.bookcool.until.TimeUtils;
public class UserTest {
@Test
public void test1() throws IOException {
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User("sss","111","男",16,"sefe@qq.com","dfdf","江西省","hello");
boolean result = mapper.addUser(user);
session.commit();
MyBatisUtil.closeSession();
if(result) {
System.out.println("增加成功...");
} else {
System.out.println("增加失败...");
}
}
@Test
public void test2() {
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.queryUser("aaa");
MyBatisUtil.closeSession();
System.out.println(user);
}
@Test
public void test3() {
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
boolean result = mapper.deleteUser("sss");
session.commit();
MyBatisUtil.closeSession();
System.out.println(result);
}
@Test
public void test4() {
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User();
user.setUpwd("333");
user.setUtel("32344");
user.setUaccount("sss");
boolean result = mapper.updateUser(user);
session.commit();
MyBatisUtil.closeSession();
System.out.println(result);
}
@Test
public void test5() {
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.queryUsers();
MyBatisUtil.closeSession();
/*for (User user : users) {
user.setUregistTime(TimeUtils.parseTime(user.getUregistTime()));
}*/
System.out.println(users);
}
}
在测试test2和test5会发现uregistTime属性的值不是标准格式的
在util包中写个转化时间的工具类TimeUtils,重新运行,格式没问题了
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 数据库timestamp类型返回时间格式转换
* @author codewen
*
*/
public class TimeUtils {
public static String parseTime(String time) {
String formatTime = null;
try {
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
} catch (ParseException e) {
System.out.println("时间转化失败!");
formatTime = "";
}
return formatTime;
}
}
持久层的用户简单的CRUD就编写完成了