5.mybatis的CURD操作
Posted 想~(●—●)肥~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5.mybatis的CURD操作相关的知识,希望对你有一定的参考价值。
5.mybatis的CURD操作
1.导包(使用maven创建工程,导包只需要配置pom.xml即可,此处导入jackson是为测试查询打印结果)
<?xml version="1.0" encoding="UTF-8"?> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>jar</packaging> <name>Mybatis01</name> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <groupId>Mybatis01</groupId> <artifactId>Mybatis01</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--junit依赖--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!--jackson2.1.0依赖--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> </dependency> <!--mysql驱动依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.43</version> </dependency> </dependencies> </project>
2.配置mybatis核心文件mybatis.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"></properties> <settings> <setting name="useGeneratedKeys" value="false"/> <setting name="useColumnLabel" value="true"/> </settings> <!-- 配置对应的javabean的路径,应用别名--> <typeAliases> <typeAlias alias="Person" type="entity.Person"/> </typeAliases> <!-- 配置数据库的连接信息 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <!--使用连接池方式获取连接--> <dataSource type="POOLED"> <!--配置数据库连接的信息--> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment> </environments> <!-- 配置映射类xml文件的路径 --> <mappers> <mapper resource="mappers/PersonMapper.xml"/> </mappers> </configuration>
3.创建sqlSession的工具类
package util; 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.Reader; /** * 工具类 * Created by Administrator on 2017/8/6. */ public class MybatisUtil { private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); private static SqlSessionFactory sqlSessionFactory; /** * 加载位于src/mybatis.xml配置文件 */ static { try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 禁止外界通过new方法直接创建,否则会不断运行影响性能 * 使用方法:将这个类的构造方法设置为私有 */ private MybatisUtil() { } /** * 获取SqlSession * * @return sqlSession */ public static SqlSession getSqlSession() { //从当前线程中获取sqlsession对象 SqlSession sqlSession = threadLocal.get(); //如果sqlSession对象为空则从sqlSessionFacety中从新获取 if (sqlSession == null) { sqlSession = sqlSessionFactory.openSession(); //将sqlSession与当前线程进行绑定 threadLocal.set(sqlSession); } return sqlSession; } /** * 关闭SqlSession与当前线程分开 */ public static void closeSqlSession() { //从当前线程中获取sqlSession SqlSession sqlSession = threadLocal.get(); //如果sqlSession不为空则关闭它,并且分离线程:如不分离线程,则会数据库操作会越来越慢 if (sqlSession != null) { sqlSession.close(); threadLocal.remove();//让GC尽快回收,释放内存 } } }
3.1测试工具类
import util.MybatisUtil; import java.sql.Connection; /** * Created by Administrator on 2017/8/6. * 测试获取qlSession */ public class test1 { public static void main(String[] args) { Connection conn = MybatisUtil.getSqlSession().getConnection(); System.out.println(conn != null?"连接成功!":"连接失败!"); } }
4.创建javabean,注意:一定要写无参的构造函数,
防止后面要使用带参的构造函数会覆盖,会出现mybatis无法创建JavaBean导致查询失败
5.配置Mapper.xml文件,并将配置文件的路径配置加到mybatis.xml中
package entity; /** * Created by Administrator on 2017/8/5. * Person的实体类 */ public class Person { private Integer id; private String name; private Integer age; private String remark; /*mybatis对应的javabean中必须得有一个默认无参的构造函数, * 如果我们自定义了有参的构造函数时,会将其覆盖,执行查询时, *mybatis无法将参数存入,所以要将其显性的写出来 */ public Person () { } //全参数的构造函数 public Person (Integer id, String name, Integer age,String remark) { super(); this.id = id; this.name = name; this.age = age; this.remark = remark; } //不含id的构造函数 public Person (String name, Integer age,String remark) { super(); this.name = name; this.age = age; this.remark = remark; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
6.书写JavaBean的Dao类
package dao; import entity.Person; import org.apache.ibatis.jdbc.SQL; import org.apache.ibatis.session.SqlSession; import util.MybatisUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Administrator on 2017/8/6. */ public class PersonDao { //*****************************************急速入门******************************************** //增加一条信息 public Integer addPerson (Person person){ try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Integer i = sqlSession.insert("Person.addPerson",person); sqlSession.commit(); return i; } catch (Exception e) { e.printStackTrace(); return -1; } finally { MybatisUtil.closeSqlSession(); } } //根据id删除人员信息 public Integer deletePersonById (int id) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Integer i = sqlSession.delete("Person.deletePersonById",id); sqlSession.commit(); return i; } catch (Exception e) { e.printStackTrace(); return -1; } finally { MybatisUtil.closeSqlSession(); } } //根据id修改一个人的信息 public Integer updatePersonById (Person person) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Integer i = sqlSession.update("Person.updatePersonById",person); sqlSession.commit(); return i; } catch (Exception e) { e.printStackTrace(); return -1; } finally { MybatisUtil.closeSqlSession(); } } //通过id获取person public Person getPersonById (int id) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Person person = sqlSession.selectOne("Person.getPersonById",id); return person; } catch (Exception e) { e.printStackTrace(); return null; } finally { MybatisUtil.closeSqlSession(); } } //根据分页查询 public List<Person> getPersonList (Integer start, Integer limit) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Map<String, Object> map = new HashMap<String, Object>(); map.put("start", start); map.put("limit", limit); List<Person> li = sqlSession.selectList("Person.getPersonList",map); return li; } catch (Exception e) { e.printStackTrace(); return null; } finally { MybatisUtil.closeSqlSession(); } } //*****************************************动态CRUD,mybatis相较于hibernate的优势******************************************** /** * 根据三个条件中的任意一个或多个进行动态查询 * @param name * @param age * @param remark * @return */ public List<Person> getPersonLList2 (String name, Integer age, String remark) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name",name); map.put("age",age); map.put("remark",remark); List<Person> li = sqlSession.selectList("Person.getPersonList2",map); return li; } catch (Exception e) { e.printStackTrace(); return new ArrayList<Person>(); } finally { MybatisUtil.closeSqlSession(); } } public Integer updatePerson1 (Person person) { try{ SqlSession sqlSession = MybatisUtil.getSqlSession(); Integer i = sqlSession.update("Person.updatePerson1",person); sqlSession.commit(); return i; }catch (Exception e) { e.printStackTrace(); return -1; }finally { MybatisUtil.closeSqlSession(); } } public Integer deletePerson1 (int... id) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Integer i = sqlSession.delete("Person.deldetPerson1",id); sqlSession.commit(); return i; } catch (Exception e) { e.printStackTrace(); return -1; } finally { MybatisUtil.closeSqlSession(); } } public Integer addPerson1 (Person person) { try { SqlSession sqlSession = MybatisUtil.getSqlSession(); Integer i = sqlSession.insert("Person.addPerson1",person); sqlSession.commit(); return i; } catch (Exception e) { e.printStackTrace(); return -1; }finally { MybatisUtil.closeSqlSession(); } } }
7.测试(其他测试类以此类推)
import util.MybatisUtil; import java.sql.Connection; /** * Created by Administrator on 2017/8/6. * 测试获取qlSession */ public class test1 { public static void main(String[] args) { Connection conn = MybatisUtil.getSqlSession().getConnection(); System.out.println(conn != null?"连接成功!":"连接失败!"); } }
8.项目文件结构
package util;
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.Reader;
/**
* 工具类
* Created by Administrator on 2017/8/6.
*/
public class MybatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlSessionFactory;
/**
* 加载位于src/mybatis.xml配置文件
*/
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 禁止外界通过new方法直接创建,否则会不断运行影响性能
* 使用方法:将这个类的构造方法设置为私有
*/
private MybatisUtil() {
}
/**
* 获取SqlSession
*
* @return sqlSession
*/
public static SqlSession getSqlSession() {
//从当前线程中获取sqlsession对象
SqlSession sqlSession = threadLocal.get();
//如果sqlSession对象为空则从sqlSessionFacety中从新获取
if (sqlSession == null) {
sqlSession = sqlSessionFactory.openSession();
//将sqlSession与当前线程进行绑定
threadLocal.set(sqlSession);
}
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession() {
//从当前线程中获取sqlSession
SqlSession sqlSession = threadLocal.get();
//如果sqlSession不为空则关闭它,并且分离线程:如不分离线程,则会数据库操作会越来越慢
if (sqlSession != null) {
sqlSession.close();
threadLocal.remove();//让GC尽快回收,释放内存
}
}
}
以上是关于5.mybatis的CURD操作的主要内容,如果未能解决你的问题,请参考以下文章