MyBatis是一个支持普通SQL查询、存储过程以及高级映射的持久层框架. MyBatis框架也被称之为ORM(Object/ Relational Mapping,即对象关系映射)框架。
ORM框架常用有两个:Hibernate和MyBatis框架。
导入相关JAR包
【通过以下网址下载:下载网址】
通过用户管理入门案例引入
创建db_mybatis数据库,一个t_user表,并插入几条数据
项目总体结构
1、通过用户id查询用户信息
在项目src下创建log4j.properties
//log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# My logging configuration...
log4j.logger.com.ssm=DEBUG
Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t]- %m%n
在com.ssm.po包下创建User类
声明相应属性,及其setter/getter方法
package com.ssm.po;
public class User {
private Integer id;
private String username;
private String jobs;
private String phone;
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public String getJobs() {
return jobs;
}
public String getPhone() {
return phone;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setJobs(String jobs) {
this.jobs = jobs;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
}
}
在com.ssm.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="com.ssm.mapper.UserMapper">
<!-- 定义重复的SQL代码片段 -->
<sql id="userColumns">id,username,jobs,phone</sql>
<!--//通过id查询用户 -->
<select id="findUserById" parameterType="Integer" resultType="com.ssm.po.User">
<!--select * from t_user where id=#{id} -->
<!-- 使用include元素的refid属性引用自定义的代码片段,属性值为自定义的代码片段id -->
select <include refid="userColumns" />
from t_user
where id=#{id}
</select>
<!-- //通过名字查询 -->
<select id="findUserByName" parameterType="String" resultType="com.ssm.po.User">
select * from t_user where username like '%${value}%'
</select>
<!--//添加用户 -->
<insert id="addUser" parameterType="com.ssm.po.User">
insert into t_user(username,jobs,phone) values(#{username},#{jobs},#{phone})
</insert>
<!--//更新用户 -->
<update id="updateUser" parameterType="com.ssm.po.User">
update t_user set username=#{username},jobs=#{jobs},phone=#{phone} where id=#{id}
</update>
<!--//删除用户 -->
<delete id="deleteUser" parameterType="Integer">
delete from t_user where id=#{id}
</delete>
</mapper>
在src下创建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>
<properties resource="db.properties" />
<!-- 1.配置环境,默认的环境id为mysql -->
<environments default="mysql">
<!-- 1.2 配置id为mysql的数据库环境 -->
<environment id="mysql">
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- 2.配置mapper的位置 -->
<mappers>
<mapper resource="com/ssm/mapper/UserMapper.xml" />
</mappers>
</configuration>
创建测试类
package com.ssm.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 com.ssm.po.User;
public class MybatisTest {
@Test
public void findUserByIdTest() throws Exception {
//1.读取配置文件
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
//2.根据配置文件构建SqlSessionFactory实例
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//3.通过SqlSessionFactory创建SqlSession实例
SqlSession sqlSession=sqlSessionFactory.openSession();
//4.SqlSession执行映射文件中定义的SQL,并返回映射结果
User user=sqlSession.selectOne("com.ssm.mapper.UserMapper.findUserById",2);
//5. 打印输出结果
System.out.println(user.toString());
//6.关闭SqlSession
sqlSession.close();
}
@Test
public void findUserByName() throws Exception{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=factory.openSession();
List<User> users=session.selectList("com.ssm.mapper.UserMapper.findUserByName","g");
for(User user:users){
System.out.println(user.toString());
}
session.close();
}
@Test
public void addUserTest() throws Exception{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=factory.openSession();
//创建User对象,向其中加入数据
User user=new User();
user.setUsername("hqx");
user.setJobs("students");
user.setPhone("123456");
//执行sqlsession的插入方法,返回受影响的行数
int rows=session.insert("com.ssm.mapper.UserMapper.addUser",user);
//判断插入操作是否执行成功
if(rows>0){
System.out.println("成功添加"+rows+"条数据");
}else{
System.out.println("添加失败");
}
//提交事务
session.commit();
//关闭
session.close();
}
@Test
public void updateUserTest() throws Exception{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=factory.openSession();
User user=new User();
user.setId(1);
user.setUsername("hjh");
user.setJobs("teacher");
user.setPhone("123456789");
int rows=session.update("com.ssm.mapper.UserMapper.updateUser",user);
if(rows>0){
System.out.println("更改成功"+rows+"条数据");
}else{
System.out.println("更新失败");
}
session.commit();
session.close();
}
@Test
public void deleteUserTest() throws Exception{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=factory.openSession();
int rows=session.delete("com.ssm.mapper.UserMapper.deleteUser",1);
if(rows>0){
System.out.println("删除成功"+rows+"条数据");
}else{
System.out.println("删除失败");
}
session.commit();
session.close();
}
}
下面展示 properties元素的使用,动态替换数据库连接配置
。
在src文件下创建db.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=root
在mybatis-config.xml中将数据库连接替换
//原本的连接数据库配置
//
//
//
//
//
//
<!-- 动态替换SQL配置 -->
<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>
总的测试类开发步骤:
//1.读取配置文件
String resource="mybatis-config.xml";
//通过输入流读取配置文件
InputStream inputStream=Resources.getResourceAsStream(resource);
//2.根据配置文件构建SqlSessionFactory实例
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//3.通过SqlSessionFactory创建SqlSession实例
SqlSession sqlSession=sqlSessionFactory.openSession();
//4.SqlSession执行映射文件中定义的SQL,并返回映射结果
User user=sqlSession.selectOne("com.ssm.mapper.UserMapper.findUserById",2);
//5. 打印输出结果
System.out.println(user.toString());
//6.关闭SqlSession
sqlSession.close();