MyBatis入门实例
关于MyBatis,不作太多介绍,在google一搜索,有很多资料,我也是参考别人的例子,MyBatis入门非常容易,希望我现在发的代码对大家有用。
实体类:
package bean;public class User {private String name;private Integer age;public User() {}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 User(String name, Integer age) {super();this.name = name;this.age = age;}}
package mapper;import org.apache.ibatis.annotations.Select;import bean.User;/** * 映射器 * */public interface UserMapper {public void insertUser(User user); //可以使用Java注解来替换XML@Select("select * from user where name=#{name}") public User getUser(String name); }
<?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="mapper.UserMapper"> <!-- 这里namespace必须是UserMapper接口的路径,不然要运行的时候要报错 “is not known to the MapperRegistry”--> <insert id="insertUser" parameterType="User"> insert into user(name,age) values(#{name},#{age}) <!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 --> </insert> <!-- 这里的id必须和UserMapper接口中的接口方法名相同,不然运行的时候也要报错 --> <!-- <select id="getUser" resultType="User" parameterType="java.lang.String"> --><!-- select * from user where name=#{name} --><!-- </select> --> </mapper>
<?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> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias alias="User" type="bean.User"/> </typeAliases> <environments default="development"> <!-- environment元素体中包含对事务管理和连接池的环境配置 --> <!-- 你可以配置多种环境,但你只能为每个SqlSessionFactory实例选择一个。 --> <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"/> <property name="username" value="root"/> <property name="password" value="123"/> </dataSource> </environment> </environments> <mappers> <mapper resource="resource/UserMapper.xml" /> </mappers> </configuration>
package utils;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisUtil {//每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心//使用SqlSessionFactory的最佳实践是在应用运行期间不要重复创建多次,最佳范围是应用范围 private final static SqlSessionFactory sqlSessionFactory; static { String resource = "resource/configuration.xml"; Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { System.out.println(e.getMessage()); } //SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来获得 //SqlSessionFactoryBuilder实例的最佳范围是方法范围(也就是本地方法变量)。 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } }
package testMapper;import mapper.UserMapper;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Test;import utils.MyBatisUtil;import bean.User;public class TestMapper {static SqlSessionFactory sqlSessionFactory = null; static { sqlSessionFactory = MyBatisUtil.getSqlSessionFactory(); } @Test public void addUser() { //获得SqlSession的实例 //每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能被共享,也是线程不安全的。因此最佳的范围是请求或方法范围。 SqlSession sqlSession = sqlSessionFactory.openSession(); try { //映射器实例的最佳范围是方法范围。 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = new User("neng",new Integer(5)); userMapper.insertUser(user); sqlSession.commit();//这里一定要提交,不然数据进不去数据库中 } finally { //确保SqlSession关闭 sqlSession.close(); } } @Test public void getUser() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.getUser("neng"); System.out.println("name: "+user.getName()+"|age: "+user.getAge()); } finally { sqlSession.close(); } } }