Mybatis 环境搭建
创建maven项目 3.6.0版本
目录结构
配置xml文件
<dependencies>
<dependency>
//mysql依赖 5.7版本
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
//mybatis依赖
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
//junit依赖
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
//lombok依赖
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
**//资源过滤 一定要加 防止资源导出失败**
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
根据数据库创建实体类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 DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values
(41,'老王','2018-02-27 17:47:08','男','北京'),
(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),
(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'),
(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),
(46,'老王','2018-03-07 17:37:26','男','北京'),
(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');
实体类:
//要加上getset方法,构造方法,tostring方法,或者用Data注解
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
**编写工具类MybatisUtils **
在测试类写也可以,为了增删改查方便,可以直接调用工具类方法
测试类可以直接调用MybatisUtils.getSqlSession获取Sqlsession
public class MybatisUtils {
//提升squSessionFactory作用域
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//第一步,读取主配置文件,创建SqlSessionFactory工厂
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//从SqlsessionFactory中获取Sqlsession实例
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
在resources包下创建mybatis-config.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>
//假如有多个环境可以改变defaul属性切换环境
<environments default="development">
//环境名字为development
<environment id="development">
// 选择驱动类型(复制改注释符号<!---->)
<transactionManager type="JDBC"/>
//配置数据源(连接池)
<dataSource type="POOLED">
//配置数据库连接信息
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis?characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
//指定映射配置文件的位置(每个Dao曾独立的配置文件)
<mappers>
//这个路径写的是 “/” 其他都是“.”
<mapper resource="com/fxy/dao/UserMapper.xml"/>
</mappers>
</configuration>
创建Dao接口UserDao
public interface UserDao {
//查询所有方法
List<User> getUserList();
}
创建Dao接口的配置文件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">
// 绑定一个对应的Dao接口 (全类名)
<mapper namespace="com.fxy.dao.UserDao">
//id为方法名,resultType为返回值类型,ParameterType为参数类型
//返回值类型写全类名
<select id="getUserList" resultType="com.fxy.pojo.User">
select * from user
</select>
在test包下新建一个测试类UserDaoTest
public class UserDaoTest {
@Test
public void test(){
//使用工具类创建的获取SqlSessionFactory工厂 获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//使用SqlSession创建Dao接口的代理对象
UserDao userDao = sqlSession.getMapper(UserDao.class);
//使用代理对象执行方法
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//释放资源
sqlSession.close();
}
根据id查找用户,添加,删除,修改,
不用动主配置文件,实体类,工具类。只需要修改Dao接口,Dao接口的配置文件,和测试类。
根据id查找
UserDao
//根据id 查找
User getUserById(int id);
Usermapper.xml
//参数类型是int 返回值是user对象
<select id="getUserById" parameterType="int" resultType="com.fxy.pojo.User">
SELECT * FROM USER WHERE id = #{id}
</select>
UserDaoTest
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao1 = sqlSession.getMapper(UserDao.class);
//参数是 id 返回值时 user对象
User user = userDao1.getUserById(41);
System.out.println(user);
sqlSession.close();
}
添加
UseDao
//添加
int addUser(User user);
Usermapper.xml
//参数是一个user对象,返回值是int数字,不写
<insert id="addUser" parameterType="com.fxy.pojo.User" >
INSERT into USER(id,username,birthday,sex,address) VALUES
(#{id},#{username}, #{birthday},#{sex},#{address})
</insert>
UserDaoTest
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao3 = sqlSession.getMapper(UserDao.class);
//i > 0 说明执行成功
int i = userDao3.addUser(new User(54,"小二王",new Date() ,"女","北京金燕龙"));
System.out.println(i);
//增删改 需要 提交事务
sqlSession.commit();
sqlSession.close();
}
删除
UseDao
//根据id删除
int deleteUserById(int id);
UserMapper.xml
<delete id="deleteUserById" parameterType="int">
delete from user where id = #{id}
</delete>
UserDaoTest
public void deleteUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao2 = sqlSession.getMapper(UserDao.class);
int i = userDao2.deleteUserById(41);
System.out.println(i);
//提交事务
sqlSession.commit();
sqlSession.close();
}
修改
UserDao
//修改
int updateUser(User user);
UserMapper.xml
<update id="updateUser" parameterType="com.fxy.pojo.User">
UPDATE USER SET username = #{username},birthday=#{birthday},sex=#{sex},address = #{address} where id = #{id}
</update>
UserDaoTest
public void update(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao4 = sqlSession.getMapper(UserDao.class);
int i = userDao4.updateUser(new User(54,"付新宇",new Date() ,"男","北京金燕龙"));
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
万能Map
当只想增加修改部分属性时可以用到Map
UserDao
//万能 map 只修改其中一个属性,不用把 整个对象传进来 sql语句只需要写需要的属性
int updateUser2(Map<String ,Object> map);
UserMapper.xml
<update id="updateUser2" parameterType="map">
UPDATE USER SET username = #{name} WHERE id = #{id}
</update>
UserDaoTest
public void update2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao4 = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("id",54);
map.put("name","王杰");
int i = userDao4.updateUser2(map);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
模糊查询
UserDao
//模糊查询
List<User> getUserLike(String value);
UserMapper.xml
<select id="getUserLike" resultType="com.fxy.pojo.User" >
SELECT * from user WHERE username like #{value}
</select>
UserDaoTest
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao5 = sqlSession.getMapper(UserDao.class);
//传进去值得两遍一定要加上%(java代码执行的时候,传递通配符)
List<User> userList2 = userDao5.getUserLike("%王%");
for (User user : userList2) {
System.out.println(user);
}
sqlSession.close();
分页查询
Ddao接口
//分页查询
List<User> getUserByLimit(Map<String,Integer> map);
Usermapper.xml
<select id="getUserByLimit" resultType="User" parameterType="map">
SELECT * from USER limit #{startIndex},#{pageSize}
</select>
UserDaoTest
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao6 = sqlSession.getMapper(UserDao.class);
Map<String,Integer> map = new HashMap<String, Integer>();
//从第几个索引开始(一号索引元素为0),每页多少个
map.put("startIndex",0);
map.put("pageSize",3);
List<User> userList3 = userDao6.getUserByLimit(map);
for (User user : userList3) {
System.out.println(user);
}
sqlSession.close();
}
RowBounds分页
Ddao接口
List<User> getUserByRowBounds();
Usermapper.xml
<!--分页2-->
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
UserDaoTest
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1, 2);
//通过Java代码层面实现分页
List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}