【MyBatis】mybatis快速入门(二)

来源:互联网 发布:通达信软件怎么用 编辑:程序博客网 时间:2024/05/24 07:31


1)创建一个mybatis-day01这么一个javaweb工程或java工程

 

2)导入mybatismysql/oraclejar包到/WEB-INF/lib目录下

asm-3.3.1.jar

cglib-2.2.2.jar

commons-logging-1.1.1.jar

log4j-1.2.16.jar

mybatis-3.1.1.jar

ojdbc5.jar

 

3)创建students.sql

--mysql语法create table students(   id  int(5) primary key,   name varchar(10),   sal double(8,2));--oracle语法create table students(   id  number(5) primary key,   name varchar2(10),   sal number(8,2));



 

4)创建Student.java

/** * 学生 * @author lfsenior */public class Student {private Integer id;private String name;private Double sal;public Student(){}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 Double getSal() {return sal;}public void setSal(Double sal) {this.sal = sal;}}



 

5)entity目录下创建StudentMapper.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"><!-- namespace属性是名称空间,必须唯一 --><mapper namespace="cn.lfsenior.javaee.mybatis.app04.Student"><!-- resultMap标签:映射实体与表 type属性:表示实体全路径名 id属性:为实体与表的映射取一个任意的唯一的名字--><resultMap type="student" id="studentMap"><!-- id标签:映射主键属性 result标签:映射非主键属性     property属性:实体的属性名     column属性:表的字段名 --><id property="id" column="id"/><result property="name" column="name"/><result property="sal" column="sal"/></resultMap><!--insert标签:要书写insert这么一个sql语句id属性:为insert这么一个sql语句取一个任意唯一的名字parameterType:要执行的dao中的方法的参数,如果是类的话,必须使用全路径类--><insert id="add1">insert into students(id,name,sal) values(1,'哈哈',7000)</insert><insert id="add2" parameterType="student">insert into students(id,name,sal) values(#{id},#{name},#{sal})</insert><insert id="add3" parameterType="student">insert into students(id,name,sal) values(#{id},#{name},#{sal})</insert></mapper>




 

6)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"/><!-- 设置类型别名 --><typeAliases><typeAlias type="cn.lfsenior.javaee.mybatis.app04.Student" alias="student"/></typeAliases><!-- 设置一个默认的连接环境信息 --><environments default="mysql_developer"><!-- 连接环境信息,取一个任意唯一的名字 --><environment id="mysql_developer"><!-- mybatis使用jdbc事务管理方式 --><transactionManager type="jdbc"/><!-- mybatis使用连接池方式来获取连接 --><dataSource type="pooled"><!-- 配置与数据库交互的4个必要属性 --><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><!-- 连接环境信息,取一个任意唯一的名字 --><environment id="oracle_developer"><!-- mybatis使用jdbc事务管理方式 --><transactionManager type="jdbc"/><!-- mybatis使用连接池方式来获取连接 --><dataSource type="pooled"><!-- 配置与数据库交互的4个必要属性 --><property name="driver" value="${oracle.driver}"/><property name="url" value="${oracle.url}"/><property name="username" value="${oracle.username}"/><property name="password" value="${oracle.password}"/></dataSource></environment></environments><!-- 加载映射文件--><mappers><mapper resource="cn/lfsenior/javaee/mybatis/app14/StudentMapper.xml"/></mappers></configuration>




 

7)util目录下创建MyBatisUtil.java类,并测试与数据库是否能连接

/** * 工具类 * @author LFSenior */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 */public static SqlSession getSqlSession(){//从当前线程中获取SqlSession对象SqlSession sqlSession = threadLocal.get();//如果SqlSession对象为空if(sqlSession == null){//在SqlSessionFactory非空的情况下,获取SqlSession对象sqlSession = sqlSessionFactory.openSession();//将SqlSession对象与当前线程绑定在一起threadLocal.set(sqlSession);}//返回SqlSession对象return sqlSession;}/** * 关闭SqlSession与当前线程分开 */public static void closeSqlSession(){//从当前线程中获取SqlSession对象SqlSession sqlSession = threadLocal.get();//如果SqlSession对象非空if(sqlSession != null){//关闭SqlSession对象sqlSession.close();//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收threadLocal.remove();}}}




 

8)在dao目录下创建StudentDao.java类并测试

/** * 持久层 * @author LFSenior */public class StudentDao {/** * 增加学生 */public void add1() throws Exception{SqlSession sqlSession = null;try{sqlSession = MybatisUtil.getSqlSession();//事务开始(默认)//读取StudentMapper.xml映射文件中的SQL语句int i = sqlSession.insert("cn.lfsenior.javaee.mybatis.app04.Student.add1");System.out.println("本次操作影响了"+i+"行");//事务提交sqlSession.commit();}catch(Exception e){e.printStackTrace();//事务回滚sqlSession.rollback();throw e;}finally{MybatisUtil.closeSqlSession();}}/** * 增加学生 */public void add2(Student student) throws Exception{SqlSession sqlSession = null;try{sqlSession = MybatisUtil.getSqlSession();//事务开始(默认)//读取StudentMapper.xml映射文件中的SQL语句sqlSession.insert(Student.class.getName()+".add2",student);//事务提交sqlSession.commit();}catch(Exception e){e.printStackTrace();//事务回滚sqlSession.rollback();throw e;}finally{MybatisUtil.closeSqlSession();}}/** * 增加学生 */public void add3(Student student) throws Exception{SqlSession sqlSession = null;try{sqlSession = MybatisUtil.getSqlSession();sqlSession.insert(Student.class.getName()+".add3",student);sqlSession.commit();}catch(Exception e){e.printStackTrace();sqlSession.rollback();throw e;}finally{MybatisUtil.closeSqlSession();}}}




 

原创粉丝点击