mybatis的使用及详解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis的使用及详解相关的知识,希望对你有一定的参考价值。
一、Mybatis介绍
MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
二、准备开发环境
导入jar包
【mybatis】
【oracle】
生成数据库
三、使用MyBatis查询表中的数据
1、添加Mybatis的配置文件conf.xml
在src目录下创建一个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> <!-- 定义一个别名们 --> <typeAliases> <!-- <typeAlias type="com.model.TestId" alias="a"/> --> <package name="com.model"/> </typeAliases> <!-- mybatis的环境们 --> <environments default="test"> <environment id="test"> <!-- mybatis支持的事务 JDBC:数据源自己的事务管理 MANAGE(托管),不支持tomcat,一般用在大型的商业服务器,weblogic,jboss --> <transactionManager type="JDBC"></transactionManager> <!-- 数据源链接类型:PLOOLED,UNOOLED,JNDI POOLED:连接池 JJNDI:使用应用服务器的数据源连接 --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> <!-- <environment id="test1"> </environment> <environment id="test2"> </environment> --> </environments> <mappers> <mapper resource="com/dao/UsersMapper.xml"/> </mappers> </configuration>
db.properties文件如下:
driver=oracle.jdbc.OracleDriver url=jdbc:oracle:thin:@localhost:1521:orcl username=root password=123
2、定义表所对应的实体类,如下图所示:
package com.model; // Generated 2017-4-19 10:19:42 by Hibernate Tools 5.2.0.CR1 import java.math.BigDecimal; import org.apache.ibatis.type.Alias; /** * TestId generated by hbm2java */ public class TestId { private BigDecimal id; private String username; private String password; public TestId() { } public TestId(BigDecimal id, String username, String password) { this.id = id; this.username = username; this.password = password; } public BigDecimal getId() { return this.id; } public void setId(BigDecimal id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TestId)) return false; TestId castOther = (TestId) other; return ((this.getId() == castOther.getId()) || (this.getId() != null && castOther.getId() != null && this.getId().equals(castOther.getId()))) && ((this.getUsername() == castOther.getUsername()) || (this.getUsername() != null && castOther.getUsername() != null && this.getUsername().equals(castOther.getUsername()))) && ((this.getPassword() == castOther.getPassword()) || (this.getPassword() != null && castOther.getPassword() != null && this.getPassword().equals(castOther.getPassword()))); } public int hashCode() { int result = 17; result = 37 * result + (getId() == null ? 0 : this.getId().hashCode()); result = 37 * result + (getUsername() == null ? 0 : this.getUsername().hashCode()); result = 37 * result + (getPassword() == null ? 0 : this.getPassword().hashCode()); return result; } }
3、定义操作test表的sql映射文件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.dao.UsersMapper"> <!-- 当数据库表字段和实体类字段不一样时重新定义的方法,在实体类中username改为username1来实验 --> <!-- <resultMap type="testId" id="user"> <result property="username1" column="USERNAME" jdbcType="number" javaType="String"/> </resultMap> <select id="list1" resultMap="user"> select * from test </select> --> <resultMap type="testId" id="users"></resultMap> <!-- 查所有表 --> <select id="list" resultType="testId"> select * from test </select> <!-- 增 --> <insert id="add" parameterType="testId"> insert into test values(sq_mybatis.nextval,#{username},#{password}) </insert> <!-- 删 --> <delete id="delete" parameterType="Integer"> delete test t where t.id=#{id} </delete> <!-- 改 --> <update id="update" parameterType="testId"> update test t set t.username=#{username},t.password=#{password} where t.id=#{id} </update> <!-- 查集合 --> <!-- <select id="selectmany" parameterType="Map" resultType="testId" > select * from test t where t.username like #{p1} and t.password like #{p2} </select> --> <select id="selectmany" parameterType="Map" resultMap="users"> select * from test t where t.username like #{p1} and t.password like #{p2} </select> </mapper>
4、创建一个MybatisUtil的和Junit的类,来进行测试
package com.util; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MybatisUtil { private static SqlSessionFactory ssf; private static SqlSession ss; public static SqlSession getSqlSession(){ InputStream in = null; //Reader reader = null; try { in= Resources.getResourceAsStream("mybatis.xml"); //reader = Resources.getResourceAsReader("mbatis.xml"); ssf= new SqlSessionFactoryBuilder().build(in); ss=ssf.openSession(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ss; } /*public static void main(String[] args){ System.out.println(getSqlSession()); }*/ }
package com.util; import static org.junit.Assert.*; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.model.TestId; public class JTest { private SqlSession ss; @Before public void setUp() throws Exception { ss= MybatisUtil.getSqlSession(); } @After public void tearDown() throws Exception { ss.commit(); ss.close(); } public void test() { List<TestId> list = ss.selectList("com.dao.UsersMapper.list"); for(TestId t : list ){ System.out.println(t.getPassword()); } } public void add(){ TestId ti = new TestId(); ti.setUsername("hahah"); ti.setPassword("321"); int n = ss.insert("com.dao.UsersMapper.add",ti); System.out.println(n); } public void delete(){ int n = ss.delete("com.dao.UsersMapper.delete",61); System.out.println(n); } public void update(){ TestId ti = new TestId(); ti.setId(new BigDecimal(41)); ti.setUsername("哈哈哈"); ti.setPassword("654321"); int n = ss.update("com.dao.UsersMapper.update",ti); System.out.println(n); } @Test public void selectmany(){ Map<String,Object> map = new HashMap<String, Object>(); map.put("p1", "张%"); map.put("p2", "2%"); List<TestId> list=ss.selectList("com.dao.UsersMapper.selectmany",map); for(TestId t:list){ System.out.println(t.getPassword()); } } }
Junit类里面实现了mybatis的增删改查的方法。
以上是关于mybatis的使用及详解的主要内容,如果未能解决你的问题,请参考以下文章
mybatis 代码生成器(IDEA, Maven)及配置详解(部分配置你应该不知道)
《深入理解mybatis原理6》 MyBatis的一级缓存实现详解 及使用注意事项