实例
pom.xml文件配置
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.xycgroupId>
<artifactId>MyBatis_Demo1artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.15version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.15version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
project>
log4j.properties文件配置
# Set root category to INFO and its only appender to CONSOLE.
# log4j.rootCategory=INFO,CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
#Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
#CONSOLE is set to be a ConsoleAppender using a Patternlayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m/n
#LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=g:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x -%m/n
SqlMapConfig.xml文件配置
<configuration>
<environments default="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/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="991016"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/xyc/dao/IUserDao.xml" />
mappers>
configuration>
User类
package com.xyc.domain;
import com.sun.xml.internal.bind.v2.model.core.ID;
import java.util.Date;
/**
* @Author: 薛云冲
* Created on 2019/7/25 22:46
*/
public class User {
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 + '\'' +
'}';
}
}
IUserDao 接口
package com.xyc.dao;
import com.sun.org.apache.xml.internal.security.Init;
import com.xyc.domain.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @Author: 薛云冲
* 用户持久层接口
* Created on 2019/7/25 22:49
*/
public interface IUserDao {
/**
* 查询所有操作
*/
//@Select("select * from user ")
List<User> findAll();
/**
* 保存用户操作
*/
boolean saveUser(User user);
/**
* 更新用户操作
* @param user
*/
boolean updateUser(User user);
/**
* 根据id删除用户信息操作
* @param userId
*/
boolean deleteUser(int userId);
/**
* 根据id查询用户信息
*/
User findById(int userId);
/**
* 根据名称模糊查询用户信息 like
* 注意在模糊查询时 传的 字符串前后 需手动加入"%"
*/
List<User>findByUserame(String username);
/**
* 用聚合函数查询总人数
**/
int findTotal();
}
IUserDao接口的映射文件IUserDao.xml
<mapper namespace="com.xyc.dao.IUserDao">
<select id="findAll" resultType="com.xyc.domain.User">
select * from user;
select>
<select id="findById" parameterType="int" resultType="com.xyc.domain.User">
SELECT * from user where id=#{id};
select>
<select id="findByUserame" resultType="com.xyc.domain.User" parameterType="String">
select * from user where username like #{username};
select>
<select id="findTotal" resultType="int">
select count(id) from user;
select>
<insert id="saveUser" parameterType="com.xyc.domain.User">
insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday});
insert>
<update id="updateUser" parameterType="com.xyc.domain.User">
update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id};
update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id};
delete>
mapper>
测试类MybatisTest.java
package com.xyc.test;
import com.mysql.cj.Session;
import com.sun.xml.internal.bind.v2.model.core.ID;
import com.xyc.dao.IUserDao;
import com.xyc.domain.User;
import junit.framework.ComparisonCompactor;
import org.apache.ibatis.annotations.Select;
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.hamcrest.Factory;
import org.junit.Test;
import org.junit.validator.PublicClassValidator;
import sun.rmi.server.UnicastServerRef;
import javax.swing.plaf.SplitPaneUI;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
/**
* @Author: 薛云冲
* Created on 2019/7/26 9:58
* mybatis 的入门案例
*/
public class MybatisTest {
@Test
// 查询所有操作
public void testFindAll() throws IOException {
//1.读取配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);
//3.使用工厂生产SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象(当dao接口实现类自写时就不用生成代理对象了,使用自己实现的类即可)
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
//使用自写的dao实现类时
//UserDaoImpl userDao = new UserDaoImpl(factory);
//5.使用代理对象执行方法
List<User> users = userDao.findAll();
//6.处理数据
System.out.println("");
for (User user : users) {
System.out.println(user);
}
//7.释放资源
sqlSession.close();
inputStream.close();
}
@Test
// 测试保存操作
public void testSaveUser() throws IOException {
User user=new User();
user.setUsername("鲁班七号");
user.setSex("男");
user.setBirthday(new Date());
user.setAddress("召唤师峡谷");
//读取配置文件,生成字节输出流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession session = factory.openSession();
//获取dao的代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//保存User
mapper.saveUser(user);
//提交事务
session.commit();
//释放资源
session.close();
inputStream.close();
}
@Test
// 测试更新操作
public void testUpdate() throws IOException {
User user = new User();
user.setId(6);
user.setUsername("鲁班七号");
user.setAddress("王者峡谷");
user.setBirthday(new Date());
user.setSex("男");
//读取配置文件,生成字节输出流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession session = factory.openSession();
//获取dao的代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//修改User
mapper.updateUser(user);
//提价事务
session.commit();
//释放资源
session.close();
inputStream.close();
}
@Test
//测试删除User信息操作
public void testDeleteUser() throws IOException {
int userId = 9;
//读取配置文件,获取字节输出资源流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession session = factory.openSession();
//获取dao代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//删除User
mapper.deleteUser(userId);
//提交事务
session.commit();
//关闭对象
session.close();
inputStream.close();
}
@Test
//测试根据id查询User信息
public void testFindById() throws IOException {
int userId=3;
//读取配置文件,获取字节输出资源流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession session = factory.openSession();
//获取dao代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//查询User信息
User user = mapper.findById(userId);
System.out.println();
System.out.println(user);
//释放资源
session.close();
inputStream.close();
}
@Test
//根据Username查询User信息
public void testFindByUsername() throws IOException {
String username = "七";
//读取配置文件,获取字节输出资源流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SplSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession对象
SqlSession session = factory.openSession();
//创建dao代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//查询User信息
List<User> users = mapper.findByUserame("%"+username+"%");
System.out.println();
for (User user : users) {
System.out.println(user);
}
//释放资源
session.close();
inputStream.close();
}
@Test
//通过聚合函数查询总人数
public void testFindTotal() throws IOException {
//读取配置文件,获取字节输出资源流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession对象
SqlSession session = factory.openSession();
//创建dao代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//查询总人数
int total = mapper.findTotal();
System.out.println();
System.out.println(total);
//释放资源
session.close();
inputStream.close();
}
}