Mybatis学习之入门
1.概述
MyBatis原本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis,MyBatis 是一个基于Java的持久层框架。iBatis提供的持久层框架包括SQL Maps和Data Access Objects(DAO), MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
2.简单DEMO
(1)User.java
public class User { private long id; private String name; private String pwd; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
(2)mybatis-configuration.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> <settings> <setting name="useGeneratedKeys" value="true" /> </settings> <typeAliases> <typeAlias type="test.User" alias="user" /> </typeAliases> <!--数据库参数配置 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="test/sys_user.xml" /> </mappers> </configuration>
(3)sys_user.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="sysuer"> <!-- 主键自增长 并且还回配置 useGeneratedKeys="true" keyProperty="fid"--> <!-- user为bean简写 配置在 mybatis-configuration.xml的typeAliases中 --> <insert id="insert" parameterType="user" useGeneratedKeys="true" keyProperty="id"> insert into sys_user(name,pwd)values(#{name},#{pwd}) </insert> </mapper>
(4)Test.java
package test; 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 Test { public static void main(String[] args) { try { String resource="mybatis-configuration.xml"; Reader reader=Resources.getResourceAsReader(resource); SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(reader); SqlSession session = factory.openSession(); User user=new User(); user.setName("zcs"); user.setPwd("111"); session.insert("sysuer.insert", user); session.commit(); System.err.println(user.getId()); } catch (Exception e) { e.printStackTrace(); } } }