1.使用Mybatis进行查询操作(crud)
1新建数据库test,导入数据表信息。
自己在数据库种添加一些信息。
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8;
2.创建Maven工程,添加依赖
<!--打包方式-->
<packaging>jar</packaging>
<!--引入相关依赖-->
<dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<!--MyBatis依赖包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--MySQL驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<!--日志包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!--测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3.创建com.hai.bean包,在此包下创建一个User类
user 类的属性如下:
package com.hai.bean;
import java.util.Date;
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//insert+alt 生成get set方法 无参构造方法,重写tostring方法,此处略
}
4.创建com.hai.Mapper包,在此包下创建一个UserMapper接口
UserMapper接口代码如下:
package com.hai.Mapper;
import com.hai.bean.User;
import java.util.List;
public interface UserMapper {
//查询所有的User用户
List<User> findAll();
}
5.在resource种创建文件目录com/hai/mapper
在资源文件夹下创建jdbc.properties文件,核心配置文件,SqlConfig.xml文件,在com/hai/mapper包下创建UserMapper映射文件
目录如图:
jdbc.properties文件 :
此处password 需要修改为你自己的数据库密码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
jdbc.username=root
jdbc.password=hwy
核心配置文件SqlConfi.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="jdbc.properties"></properties>
<typeAliases>
<typeAlias alias="user" type="com.hai.bean.User" ></typeAlias>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hai/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
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="com.hai.mapper.UserMapper">
<select id="findAll" parameterType="com.hai.bean.User" resultType="com.hai.bean.User">
select * from `user`;
</select>
</mapper>
6.编写测试类代码
在测试包下 编写测试包com.hai.test ,在该包下编写测试类test
结构如下:
测试类代码如下:
package com.hai.test;
import com.hai.bean.User;
import com.hai.mapper.UserMapper;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class test {
@Test
public void FindAll() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//查询测试
List<User> all = mapper.findAll();
for (User u :all) {
System.out.println(u);
}
}
}
点击运行,运行结果如下:
这样我们就做好了查询的工作。
7.简单小结步骤
- 创建maven项目
- 添加依赖
- 新建实体类和对应接口
- 编写数据源文件jdbc.properties,核心配置文件SqlConfig.xml,映射文件UserMapper.xml
- 编写测试类,测试运行。
2. 添加、删除和修改操作。
做完上面的步骤,就可以快速写添加、删除,修改操作
UserMapper接口添加方法
package com.hai.mapper;
import com.hai.bean.User;
import java.util.List;
public interface UserMapper {
//查询所有的User用户
List<User> findAll();
//添加
Integer insert(User user);
//删除
int delete(int id);
//修改
int update(User user);
}
UserMapper.xml加入以下代码:
<insert id="insert" parameterType="com.hai.bean.User">
insert into `user` values (#{id},#{username},#{birthday},#{sex},#{address});
</insert>
<delete id="delete" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="update" parameterType="com.hai.bean.User">
update user set username=#{username} where id= #{id}
</update>
测试类 ,添加功能测试方法:
//添加
@Test
public void insert() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Date date = new Date();
User user = new User(2, "Allen", date, "男", "深圳");
Integer integer=mapper.insert(user);
sqlSession.commit();//提交
System.out.println(integer);
}
结果:
修改功能测试方法:
@Test
public void update() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//根据id修改名字
User user = new User();
user.setId(2);
user.setUsername("海文宇");
int i= mapper.update(user);
sqlSession.commit();//提交
System.out.println(i);
}
测试结果:
删除功能测试:
//删除
@Test
public void delete() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlConfig.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id=2;
int i =mapper.delete(id);
sqlSession.commit();//提交
System.out.println(i);
}
结果:
3.进一步改进
编写工具类,减少代码的重复性。
package com.hai.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 {
private static SqlSessionFactory sqlSessionFactory;
private static SqlSession session;
static {
try {
String resource = "SqlConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//获取工厂对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
//获取对象 openSession括号丽可以填写true,表示自动提交
session = sqlSessionFactory.openSession();
return session;
}
//关闭资源
public static void closeCommit() {
if (session != null) {
session.commit();
session.close();
}
}
public static void closeNotCommit() {
if (session != null) {
session.close();
}
}
}
改进后的测试类代码如下:
package com.hai.test;
import com.hai.bean.User;
import com.hai.mapper.UserMapper;
import com.hai.utils.MybatisUtils;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class test {
//查询
@Test
public void FindAll() throws IOException {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
//查询测试
List<User> all = mapper.findAll();
for (User u :all) {
System.out.println(u);
}
}
//添加
@Test
public void insert() throws IOException {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
Date date = new Date();
User user = new User(2, "Allen", date, "男", "深圳");
Integer integer=mapper.insert(user);
MybatisUtils.closeCommit();//提交
System.out.println(integer);
}
//删除
@Test
public void delete() throws IOException {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int id=2;
int i =mapper.delete(id);
MybatisUtils.closeCommit();//提交
System.out.println(i);
}
//修改
@Test
public void update() throws IOException {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
//根据id修改名字
User user = new User();
user.setId(2);
user.setUsername("海文宇");
int i= mapper.update(user);
MybatisUtils.closeCommit();//提交
System.out.println(i);
}
}
4.添加日志文件,方便查看
在资源文件夹下新建日志文件log4j.properties
目录如下
log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
执行查询结果如下