首页 > 代码库 > Mybatis 3.2.7 简单入门Demo
Mybatis 3.2.7 简单入门Demo
对最新版本 Mybatis 3.2.7 做了一个demo,做个记录
需要的基本jar:
mybatis-3.2.7.jar
mysql-connector-java-5.1.27.jar
首先配置xml文件
mybatis-config.xml
需要的基本jar:
mybatis-3.2.7.jar
mysql-connector-java-5.1.27.jar
首先配置xml文件
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="resources/config.properties" /> <settings> <setting name="cacheEnabled" value=http://www.mamicode.com/"true" />>
CustomerMapper.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="model.Customer"> <resultMap id="customerResultMap" type="model.Customer"> <id property="id" column="id" /> <result property="name" column="username" /> <result property="age" column="age" /> <result property="des" column="des" /> </resultMap> <!-- 用来定义可重用的 SQL 代码段,可以包含在其他语句中。 --> <sql id="customerColumns"> name,age,des </sql> <select id="selectCustomerAll3" resultType="Customer"> select <include refid="customerColumns" /> from customers </select> <!-- useGeneratedKey ( 仅 对 insert, update 有 用 ) 这 会 告 诉 MyBatis 使 用 JDBC 的 getGeneratedKeys 方法来取出由数据 (比如:像 MySQL 和 SQL Server 这样的数据库管理系统的自动递增字段)内部生成的主键。 默认值:false。 <selectKey keyProperty="id" resultType="int" order="BEFORE"> select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1 </selectKey> #{property,javaType=int,jdbcType=NUMERIC} ORDER BY ${columnName} 这里 MyBatis 不会修改或转义字符串。 --> <insert id="saveCustomer" parameterType="model.Customer" useGeneratedKeys="true" keyProperty="id" flushCache="true"> insert into customers(name,age,des) values (#{name}, #{age}, #{des}) </insert> <select id="selectCustomerAll" resultType="Customer" flushCache="false" useCache="true"> select id,name,age,des from customers </select> <!-- 数组 : <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> #{item} </foreach> --> <select id="selectCustomer3" resultType="Customer"> SELECT id,name,age,des FROM customers WHERE id in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{id} </foreach> </select> <select id="selectCustomerByBind" parameterType="Customer" resultType="Customer"> <!-- <bind name="pattern" value=http://www.mamicode.com/"'%' + ${name} + '%'" /> 此未测试成功 -->>
Customer.javapackage model; public class Customer { public int id; public String name; public int age; public String des; public Customer() { } public Customer(int id, String name, int age, String des) { this.id = id; this.name = name; this.age = age; this.des = des; } public Customer(String name, int age, String des) { this.name = name; this.age = age; this.des = des; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", age=" + age + ", des=" + des + "]"; } }
SessionFactoryUtil.javapackage dao; import java.io.IOException; import java.io.InputStream; 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 SessionFactoryUtil { private static final String MYBATIS_CONFIG_PATH = "resources/mybatis-config.xml"; private static InputStream is = null; private static SqlSessionFactory sqlSessionFactory = null; static { try { is = Resources.getResourceAsStream(MYBATIS_CONFIG_PATH); //SqlSessionFactoryBuilder这个类可以被实例化,使用和丢弃。一旦创建了 SqlSessionFactory 后,这个类就不需 要存在了。 //因此 SqlSessionFactoryBuilder 实例的最佳范围是方法范围 (也就是本地方法变量)。 sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } } /** * 私有构造器 */ private SessionFactoryUtil(){}; /** * SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次 * 最简单的就是使用单例模式或者静态单例模式。 * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactoryIntance(){ return sqlSessionFactory; } /** * 每个线程都应该有它自己的 SqlSession 实例。 * SqlSession 的实例不能被共享,也是线程 不安全的。 * 因此最佳的范围是请求或方法范围。 * 绝对不能将 SqlSession 实例的引用放在一个 类的静态字段甚至是实例字段中。 * @return SqlSession */ public static SqlSession getSqlSessionIntance() { return sqlSessionFactory.openSession(); } }
测试:package dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import model.Customer; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class CustomerDao { public CustomerDao() { } @Test public void findCustomer() { //SqlSessionFactory ssf = null; SqlSession sqlSession = null; try { //ssf = SessionFactoryUtil.getSqlSessionFactoryIntance(); sqlSession = SessionFactoryUtil.getSqlSessionIntance(); System.out.println(sqlSession); //每次都是新建一个SqlSession实例org.apache.ibatis.session.defaults.DefaultSqlSession@dc57db //sqlSession = SessionFactoryUtil.getSqlSessionIntance(); //System.out.println(sqlSession); //每次都是新建一个SqlSession实例org.apache.ibatis.session.defaults.DefaultSqlSession@c24c0 //resultType="hashmap" 返回类型为 Map<id,Map<列名,值>> Map<Object, Object> customerMap = (Map<Object, Object>) sqlSession.selectMap("selectCustomerAll2", "id"); System.out.println("customerMap : " + customerMap); for(Map.Entry<Object, Object> customerSingle : customerMap.entrySet()) { System.out.println("customerMap : " + customerSingle); System.out.println("customerMap_Key : " + customerSingle.getKey()); System.out.println("customerMap_Value : " + customerSingle.getValue()); @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) customerSingle.getValue(); System.out.println("Name : " + map.get("name")); } //resultType="Customer" 自动封装成 list //如果没有查到数据,返回长度为0的list //List<Customer> customerList = sqlSession.selectList("selectCustomerAll"); //测试 bind 用于 like 查询 Customer customerBind = new Customer("Man",110,"service"); List<Customer> customerList = sqlSession.selectList("selectCustomerByBind", customerBind); System.out.println("customerList : " + customerList); System.out.println("customerList : " + customerList.size()); List<Customer> customerList1 = new ArrayList<Customer>(); System.out.println("customerList1 : " + customerList1); System.out.println("customerList1 : " + customerList1.size()); for (Customer customer : customerList) { System.out.println(customer); } } catch (Exception e) { e.printStackTrace(); } finally { if(sqlSession != null) { sqlSession.close(); } } } @Test public void saveCustomer() { SqlSession sqlSession = null; try { sqlSession = SessionFactoryUtil.getSqlSessionIntance(); Customer customer = new Customer("herry",110,"service"); int id = sqlSession.insert("saveCustomer", customer); //返回影响的行数 System.out.println(id); System.out.println(customer.getId()); //id 已经被set为 自增长的 key sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); sqlSession.rollback(); }finally { sqlSession.close(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。