目录
- 1. 简介
- 2. 配置
- 3. doing
- 3.1 创建一个表
- 3.2 打开IDEA,创建一个maven项目
- 3.3 导入依赖的jar包
- 3.4 创建entity
- 3.5 编写mapper映射文件(编写SQL)
- 3.6 编写主配置文件
- 3.7 编写接口
- 3.8 测试
- 参考链接
1. 简介
它是一款半自动的ORM持久层框架,具有较高的SQL灵活性,支持高级映射(一对一,一对多),动态SQL,延迟加载和缓存等特性,但它的数据库无关性较低。
2. 配置
- 编写全局配置文件
- 编写mapper映射文件
- 加载全局配置文件,生成SqlSessionFactory
- 创建SqlSession,调用mapper映射文件中的SQL语句来执行CRUD操作
3. doing
3.1 创建一个表
这就不提了
3.2 打开IDEA,创建一个maven项目
3.3 导入依赖的jar包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
3.4 创建entity
package com.qcby.entity;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private static final long serialVersionUID = 525400707336671154L;
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
3.5 编写mapper映射文件(编写SQL)
<?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.qcby.dao.UserDao">
<select id="findAll" resultType="user">
select * from userx;
</select>
<!--
通过id查询
SQL语句使用#{占位符的名称,名称可以任意},仅限于基本数据类型和String类型
-->
<select id="findById" resultType="com.qcby.entity.User" parameterType="int">
select * from userx where id = #{id};
</select>
<!--保存操作-->
<insert id="insert" parameterType="com.qcby.entity.User">
/*
keyProperty表示要返回的属性名称
order取值AFTER表示插入数据后的行为
resultType表示返回值的类型
*/
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id();
</selectKey>
insert into userx (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 修改 -->
<update id="update" parameterType="com.qcby.entity.User">
update userx set username = #{username},birthday = #{birthday},sex = #{sex},address=#{address} where id = #{id}
</update>
<!-- 删除 -->
<delete id="delete" parameterType="Integer">
delete from userx where id = #{id}
</delete>
<!-- 模糊查询 -->
<select id="findByName" resultType="com.qcby.entity.User" parameterType="string">
<!-- 第一种方式的SQL语句
select * from user where username like #{username}
-->
<!-- 第二章SQL语句的编写 强调:'%${value}%'不能修改,固定写法(不推荐使用) -->
select * from userx where username like '%${value}%'
</select>
<!-- 具体函数的查询 -->
<select id="findByCount" resultType="int">
select count(*) from userx
</select>
</mapper>
3.6 编写主配置文件
<?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>
<!-- 别名 注意位置-->
<typeAliases>
<!-- 把com.qcbyjy.domain.User使用user别名来显示,别名user User USER都可以,默认是忽略大写的
<typeAlias type="com.qcbyjy.domain.User" alias="user"/>
-->
<!-- 针对com.qcbyjy.domain包下的所有的类,都可以使用当前的类名做为别名 -->
<package name="com.qcby.entity"/>
</typeAliases>
<!-- 配置环境们 -->
<environments default="mysql">
<!-- 配置具体的环境 -->
<environment id="mysql">
<!-- 配置事务管理类型 -->
<transactionManager type="JDBC"/>
<!-- 配置是否需要使用连接池,POOLED使用,UNPOOLED不使用 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射的配置文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
3.7 编写接口
package com.qcby.dao;
import com.qcby.entity.User;
import java.util.List;
public interface UserDao {
List<User> findAll();
public User findById(Integer userId);
public void insert(User user);
public void update(User user);
public void delete(Integer userId);
public List<User> findByName(String username);
public Integer findByCount();
}
3.8 测试
UserTest.java
package com.qcby.demo;
import com.qcby.dao.UserDao;
import com.qcby.entity.User;
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.InputStream;
import java.util.List;
public class UserTest {
@Test
public void testFindAll() throws Exception {
// 加载主配置文件,目的是构建SqlSessionFactory的对象
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 使用SqlSessionFactory工厂对象创建SqlSession对象
SqlSession session = factory.openSession();
// 通过session创建UserMapper接口的代理对象
UserDao mapper = session.getMapper(UserDao.class);
// 调用查询所有的方法
List<User> list = mapper.findAll();
// 遍历集合
for (User user : list) {
System.out.println(user);
}
// 释放资源
session.close();
in.close();
}
@Test
public void run2() throws Exception {
// 加载配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 构建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取到session对象
SqlSession session = factory.openSession();
// 查询所有的数据
List<User> list = session.selectList("com.qcby.dao.UserDao.findAll");
// 变量集合
for (User user : list) {
System.out.println(user);
}
// 关闭资源
session.close();
inputStream.close();
}
}
运行结果:
UserTest2.java
package com.qcby.demo;
import com.qcby.dao.UserDao;
import com.qcby.entity.User;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class UserTest2 {
private InputStream in;
private SqlSession session;
private UserDao mapper;
@Before
public void init() throws Exception {
// 加载配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建工厂对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建Session对象
session = factory.openSession();
// 获取到代理对象
mapper = session.getMapper(UserDao.class);
}
@After
public void destory() throws IOException {
in.close();
session.close();
}
@Test
public void testFindAll() throws Exception {
List<User> list = mapper.findAll();
// 遍历
for (User user : list) {
System.out.println(user);
}
in.close();
}
@Test
public void testFindById() throws Exception {
User user = mapper.findById(41);
System.out.println(user);
in.close();
}
@Test
public void testInsert() throws Exception {
User user = new User();
user.setUsername("美美");
user.setBirthday(new Date());
user.setSex("男");
user.setAddress("顺义");
mapper.insert(user);
session.commit();
System.out.println(user.getId());
}
@Test
public void testUpdate() throws Exception {
User user = mapper.findById(41);
user.setUsername("小凤");
mapper.update(user);
session.commit();
}
@Test
public void testDelete() throws Exception {
mapper.delete(48);
session.commit();
}
// 第一种
/* @Test
public void testFindByName() throws Exception {
List<User> list = mapper.findByName("%王%");
for (User user : list) {
System.out.println(user);
}
}*/
// 第二种
@Test
public void testFindByName() throws Exception {
List<User> list = mapper.findByName("王");
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testFindByCount() throws Exception {
Integer count = mapper.findByCount();
System.out.println("总记录数:" + count);
}
}
参考链接
mybatis看这一篇就够了,简单全面一发入魂
MyBatis从入门到精通