MyBatis 基础配置
刚学MyBatis,第一件事先来个Hello Word实现
1.写个实体类
package com.maya.model; public class Student { private int id; private String name; private int age; 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 Student(String name, int age) { super(); this.name = name; this.age = age; } public Student() { super(); } }
2.数据源,db.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=GBK userName=root password=
3.定义接口
package com.maya.mappers; import com.maya.model.Student; public interface StudentMapper { public int add(Student student); }
4.开始mybatis的配置
<?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> <!-- 1.数据源的引用 --> <properties resource="db.properties"/><!-- 引入资源文件 --> <!-- 如果你不想引入资源文件,而是直接在这里面写的话,就要通过配置properties来进行配置 --> <!-- <properties> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=GBK"/> <property name="userName" value="root"/> <property name="password" value=""/> </properties> --> <!-- 2.取别名 --> <!-- <typeAliases> <typeAlias alias="Student" type="com.maya.model.Student"/> alias是别名的意思,当然如果有100个类,难道要写一百个别名?,这肯定是不可取得 </typeAliases> --> <!-- 为了规避上面的的问题,通常采用这个方式来实现别名,通过扫描这个包下的所有实体类来自动生成别名。 当然别名肯定是类名,这是一种规范 --> <typeAliases> <package name="com.maya.model"/> </typeAliases> <!-- 3.环境 --> <environments default="development"><!-- 环境,一般企业最少三个环境,开发环境、测试环境、正式环境 --> <environment id="development"> <transactionManager type="JDBC" /><!-- 事务管理,通常有两种,一种是JDBC另一种是MANAGED--> <dataSource type="POOLED"><!-- 连接池,引入数据源 :类型有三种1.UNPOOLED,2.POOLED,3.JNDI。最常用的就是POOLED--> <property name="driver" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${userName}" /> <property name="password" value="${password}" /> </dataSource> </environment> <environment id="test"><!-- 例如这是一个测试环境 ,那么只需要environments的default属性改成test就可以了--> <transactionManager type="JDBC" /><!-- 事务管理,JDBC--> <dataSource type="POOLED"><!-- 连接池,引入数据源 --> <property name="driver" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${userName}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- 4.映射器 --> <mappers><!-- 映射器 --> <!-- 下面这种2种方式和生成别名是一个道理,如果是大项目的话,同样是不可取的,不可能一个一个来配置映射文件 --> <!-- <mapper resource="com/maya/mappers/StudentMapper.xml" /> --> <!-- <mapper class="com.maya.mappers.StudentMapper" /> --> <package name="com.maya.mappers"/> </mappers> </configuration>
扩展:
1.关于transactionManager
MayBatis支持两种类型事务管理器:JDBC 和 MANAGED(托管);
JDBC:应用程序负责管理数据库连接的生命周期;
MANAGED:有应用服务器负责管理数据库连接的生命周期;(一般商业服务器才有此功能,例如JBOSS,WebLogic),当然tomcat是没有这个功能的,并且这个是要收费的
2.dataSource
用来配置数据源的类型有:UNPOOLED,POOLED,JNDI;
UNPOOLED,没有连接池,每次数据库操作,MyBatis都会创建一个新的链接,用完后,关闭,适合于小项目;
POOLED,用上了连接池;
JNDI,使用应用服务器配置JNDI数据源获取数据库连接;
5.mapper映射实现
<?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.maya.mappers.StudentMapper"> <insert id="add" parameterType="Student" ><!-- id方法名,parameterType别名,如果不写别名就要写完成限定名 --> insert into student values(null,#{name},#{age})<!-- 在这里写语句 --> </insert> </mapper>
6.日志文件
log4j.rootLogger=info,appender1,appender2
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender2=org.apache.log4j.FileAppender
log4j.appender.appender2.File=C:/logFile.txt
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout
7.SqlSessionFactory工具类
package com.maya.util; 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 SqlSessionFactoryUtil { private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory getsqlSessionFactory(){ if(sqlSessionFactory==null){ InputStream inputStream=null; try { inputStream=Resources.getResourceAsStream("mybatis-config.xml");//读取配置文件 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } return sqlSessionFactory; } public static SqlSession openSession(){ return getsqlSessionFactory().openSession(); } }
8.测试类
package com.maya.service; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import com.maya.mappers.StudentMapper; import com.maya.model.Student; import com.maya.util.SqlSessionFactoryUtil; public class StudentTest { private static Logger logger=Logger.getLogger(StudentTest.class); public static void main(String[] args){ SqlSession sqlSession=SqlSessionFactoryUtil.openSession(); StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class); Student student=new Student("王10",13); int result=studentMapper.add(student); sqlSession.commit(); if(result>0){ logger.info("添加成功!"); } } }
transactionManager