MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。 |
CREATE TABLE `hero`
(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL,
`sex` CHAR(2),
`designation` VARCHAR(64),
reaking INT(10),
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
4.0.0
cn.jdbc
mybatis10
1.0-SNAPSHOT
junit
junit
4.10
org.mybatis
mybatis
3.2.8
mysql
mysql-connector-java
5.1.28
log4j
log4j
1.2.12
src/main/java
**/*.xml
log4j.rootLogger=DEBUG,CONSOLE,file
log4j.logger.cn.smbms.dao=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error
package cn.jdbc.entity;
public class Name {
private Integer id;//id
private Integer reaking;//排名
private String name;//姓名
private String sex;//性别
private String desigNation;//称号
@Override
public String toString() {
return "Name{" +
"id=" + id +
", reaking=" + reaking +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", desigNation='" + desigNation + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getReaking() {
return reaking;
}
public void setReaking(Integer reaking) {
this.reaking = reaking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getDesigNation() {
return desigNation;
}
public void setDesigNation(String desigNation) {
this.desigNation = desigNation;
}
}
public class TuserTest {
@Test
//查询用户总数
//第一种老方法输出,未优化前
public void queryCountTest() {
SqlSession sqlSession = null;
try {
//获取mybatis-config.xml的输入流
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder工厂
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//sqlSessionFactory读取配置文件
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
//开启sqlSession,执行mapper中的操作
sqlSession = sqlSessionFactory.openSession();
//把mapper文件引入到mybatis-config.xml中
int n = sqlSession.selectOne("cn.jdbc.dao.TuserMapper.queryCount");
System.out.println(n);
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
sqlSession.close();
}
}
}
package cn.jdbc.util;
import jdk.internal.util.xml.impl.Input;
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 MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//公用的代码
InputStream inputStream=Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//开启sqlSession,执行mapper中的操作
public static SqlSession createSqlSession(){
return sqlSessionFactory.openSession();
}
//关闭资源
public static void closeSqlSession(SqlSession sqlSession){
if(sqlSession!=null){
sqlSession.close();
}
}
}
package cn.jdbc.dao;
import cn.jdbc.entity.Name;
import java.util.List;
public interface TuserMapper {
//查询全部用户信息
List queryAll();
//模糊查询,查询通过用户名查询用户信息
List getUserListByUserName(String name);
//模糊查询,多参数查询用实体类进行入参
List getUserListByUserNameAndNickName(Name name);
//修改数据
public Integer updateTuser(Name name);
//删除用户数据
Integer deleteTuserByid(Integer id);
//插入数据
Integer addTuser(Name name);
}
测试的两种方法1.直接类里调用 2.直接调用接口中的方法
测试类
@Test
//获取全部用户信息
//简化版
public void queryALLTest(){
SqlSession sqlSession=null;
sqlSession=MybatisUtil.createSqlSession();
//第一种方法 通过路径获取信息
// List n=sqlSession.selectList("cn.jdbc.dao.TuserTest.queryAll");
//第二种方法 通过接口返回信息引入映射文件中
List n=sqlSession.getMapper(TuserMapper.class).queryAll();
if(n!=null){
for (Name tuser : n) {
System.out.println(tuser);
}
}
}
insert into hero (name, reaking, designation)
values (#{name}, #{reaking}, #{desigNation})
@Test
//添加
public void addTuser(){
SqlSession sqlSession=null;
Name name =new Name();
name.setReaking(11);
name.setDesigNation("扑天雕");
name.setName("李应");
int rows=0;
sqlSession = MybatisUtil.createSqlSession();
rows=sqlSession.getMapper(TuserMapper.class).addTuser(name);
sqlSession.commit();
if(rows>0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
MybatisUtil.closeSqlSession(sqlSession);
}
UPDATE hero SET
name=#{name},
designation=#{desigNation},
reaking=#{reaking}
WHERE
id=#{id}
测试
//修改
public void testUpdateTuser(){
SqlSession sqlSession=null;
Name name =new Name();
name.setReaking(10);
name.setName("柴进");
name.setDesigNation("排行第十");
name.setId(10);
int rows=0;
sqlSession = MybatisUtil.createSqlSession();
rows=sqlSession.getMapper(TuserMapper.class).updateTuser(name);
sqlSession.commit();
if(rows>0){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
MybatisUtil.closeSqlSession(sqlSession);
}
delete from hero where id=#{id}
测试
@Test
//删除
public void testDeletTuserByid(){
SqlSession sqlSession=null;
int delete=0;
sqlSession = MybatisUtil.createSqlSession();
delete=sqlSession.getMapper(TuserMapper.class).deleteTuserByid(11);
sqlSession.commit();
if(delete>0){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
MybatisUtil.closeSqlSession(sqlSession);
}
测试代码
@Test
//模糊查询,查询通过用户名查询用户信息
public void testGetUserListByuserNameTest() {
SqlSession sqlSession = null;
sqlSession = MybatisUtil.createSqlSession();
List list = sqlSession.getMapper(TuserMapper.class).getUserListByUserName("宋江");
if (null != list) {
for (Name name : list) {
System.out.println(name);
}
}
MybatisUtil.closeSqlSession(sqlSession);
}
@Test
//模糊查询,多参数查询用实体类进行入参
public void testGetUserByUserListByUserNameAndNickName(){
SqlSession sqlSession=null;
List list=null;
Name tuser =new Name();
tuser.setName("林冲");
tuser.setDesigNation("豹子头");
sqlSession = MybatisUtil.createSqlSession();
list=sqlSession.getMapper(TuserMapper.class).getUserListByUserNameAndNickName(tuser);
if(null!=list){
for (Name tuser1 : list) {
System.out.println(tuser1);
}
}
MybatisUtil.closeSqlSession(sqlSession);
}
结语:第一次写博客,尽然写了一夜,至努力的自己