Java+Spring+MySql环境中安装和配置MyBatis的教程
作者:limingnihao 发布时间:2024-01-12 23:23:48
1.MyBatis简介与配置MyBatis+Spring+MySql
1.1MyBatis简介
MyBatis 是一个可以自定义SQL、存储过程和高级映射的持久层框架。MyBatis 摒除了大部分的JDBC代码、手工设置参数和结果集重获。MyBatis 只使用简单的XML 和注解来配置和映射基本数据类型、Map 接口和POJO 到数据库记录。相对Hibernate和Apache OJB等“一站式”ORM解决方案而言,Mybatis 是一种“半自动化”的ORM实现。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(与Spring结合包)。
下载地址:
http://ibatis.apache.org/tools/ibator
http://code.google.com/p/mybatis/
1.2MyBatis+Spring+MySql简单配置
1.2.1搭建Spring环境
(1)建立maven的web项目;
(2)加入Spring框架、配置文件;
(3)在pom.xml中加入所需要的jar包(spring框架的、mybatis、mybatis-spring、junit等);
(4)更改web.xml和spring的配置文件;
(5)添加一个jsp页面和对应的Controller;
(6)测试。
可参照:http://limingnihao.iteye.com/blog/830409。使用Eclipse的Maven构建SpringMVC项目
1.2.2建立MySql数据库
建立一个学生选课管理数据库。
表:学生表、班级表、教师表、课程表、学生选课表。
逻辑关系:每个学生有一个班级;每个班级对应一个班主任教师;每个教师只能当一个班的班主任;
使用下面的sql进行建数据库,先建立学生表,插入数据(2条以上)。
更多sql请下载项目源文件,在resource/sql中。
/* 建立数据库 */
CREATE DATABASE STUDENT_MANAGER;
USE STUDENT_MANAGER;
/***** 建立student表 *****/
CREATE TABLE STUDENT_TBL
(
STUDENT_ID VARCHAR(255) PRIMARY KEY,
STUDENT_NAME VARCHAR(10) NOT NULL,
STUDENT_SEX VARCHAR(10),
STUDENT_BIRTHDAY DATE,
CLASS_ID VARCHAR(255)
);
/*插入学生数据*/
INSERT INTO STUDENT_TBL (STUDENT_ID,
STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
CLASS_ID)
VALUES (123456,
'某某某',
'女',
'1980-08-01',
121546
)
创建连接MySql使用的配置文件mysql.properties。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8
1.2.3搭建MyBatis环境
顺序随便,现在的顺序是因为可以尽量的少的修改写好的文件。
1.2.3.1创建实体类: StudentEntity
public class StudentEntity implements Serializable {
private static final long serialVersionUID = 3096154202413606831L;
private ClassEntity classEntity;
private Date studentBirthday;
private String studentID;
private String studentName;
private String studentSex;
public ClassEntity getClassEntity() {
return classEntity;
}
public Date getStudentBirthday() {
return studentBirthday;
}
public String getStudentID() {
return studentID;
}
public String getStudentName() {
return studentName;
}
public String getStudentSex() {
return studentSex;
}
public void setClassEntity(ClassEntity classEntity) {
this.classEntity = classEntity;
}
public void setStudentBirthday(Date studentBirthday) {
this.studentBirthday = studentBirthday;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public void setStudentSex(String studentSex) {
this.studentSex = studentSex;
}
}
1.2.3.2创建数据访问接口
Student类对应的dao接口:StudentMapper。
public interface StudentMapper {
public StudentEntity getStudent(String studentID);
public StudentEntity getStudentAndClass(String studentID);
public List<StudentEntity> getStudentAll();
public void insertStudent(StudentEntity entity);
public void deleteStudent(StudentEntity entity);
public void updateStudent(StudentEntity entity);
}
1.2.3.3创建SQL映射语句文件
Student类的sql语句文件StudentMapper.xml
resultMap标签:表字段与属性的映射。
Select标签:查询sql。
<?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.manager.data.StudentMapper">
<resultMap type="StudentEntity" id="studentResultMap">
<id property="studentID" column="STUDENT_ID"/>
<result property="studentName" column="STUDENT_NAME"/>
<result property="studentSex" column="STUDENT_SEX"/>
<result property="studentBirthday" column="STUDENT_BIRTHDAY"/>
</resultMap>
<!-- 查询学生,根据id -->
<select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBL ST
WHERE ST.STUDENT_ID = #{studentID}
]]>
</select>
<!-- 查询学生列表 -->
<select id="getStudentAll" resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap">
<![CDATA[
SELECT * from STUDENT_TBL
]]>
</select>
</mapper>
1.2.3.4创建MyBatis的mapper配置文件
在src/main/resource中创建MyBatis配置文件:mybatis-config.xml。
typeAliases标签:给类起一个别名。com.manager.data.model.StudentEntity类,可以使用StudentEntity代替。
Mappers标签:加载MyBatis中实体类的SQL映射语句文件。
<?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>
<typeAliases>
<typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/>
</typeAliases>
<mappers>
<mapper resource="com/manager/data/maps/StudentMapper.xml" />
</mappers>
</configuration>
1.2.3.5修改Spring 的配置文件
主要是添加SqlSession的制作工厂类的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和数据访问接口对应的实现bean。通过MapperFactoryBean创建出来。需要执行接口类全称和SqlSession工厂bean的引用。
<!-- 导入属性配置文件 -->
<context:property-placeholder location="classpath:mysql.properties" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!— mapper bean -->
<bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean">
<property name="mapperInterface" value="com.manager.data.StudentMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
也可以不定义mapper的bean,使用注解:
将StudentMapper加入注解
@Repository
@Transactional
public interface StudentMapper {
}
对应的需要在dispatcher-servlet.xml中加入扫描:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>
<property name="basePackage" value="com.liming.manager"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
1.2.4测试StudentMapper
使用SpringMVC测试,创建一个TestController,配置tomcat,访问index.do页面进行测试:
@Controller
public class TestController {
@Autowired
private StudentMapper studentMapper;
@RequestMapping(value = "index.do")
public void indexPage() {
StudentEntity entity = studentMapper.getStudent("10000013");
System.out.println("name:" + entity.getStudentName());
}
}
使用Junit测试:
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "test-servlet.xml")
public class StudentMapperTest {
@Autowired
private ClassMapper classMapper;
@Autowired
private StudentMapper studentMapper;
@Transactional
public void getStudentTest(){
StudentEntity entity = studentMapper.getStudent("10000013");
System.out.println("" + entity.getStudentID() + entity.getStudentName());
List<StudentEntity> studentList = studentMapper.getStudentAll();
for( StudentEntity entityTemp : studentList){
System.out.println(entityTemp.getStudentName());
}
}
}
2.MyBatis的主配置文件
在定义sqlSessionFactory时需要指定MyBatis主配置文件:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
MyBatis配置文件中大标签configuration下子标签包括:
configuration
|--- properties
|--- settings
|--- typeAliases
|--- typeHandlers
|--- objectFactory
|--- plugins
|--- environments
|--- |--- environment
|--- |--- |--- transactionManager
|--- |--- |__ dataSource
|__ mappers
2.1 properties属性
properties和java的.properties的配置文件有关。配置properties的resource指定.properties的路径,然后再在properties标签下配置property的name和value,则可以替换.properties文件中相应属性值。
<!-- 属性替换 -->
<properties resource="mysql.properties">
<property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.url" value="jdbc:mysql://localhost:3306/student_manager"/>
<property name="username" value="root"/>
<property name="password" value="limingnihao"/>
</properties>
2.2 settings设置
这是MyBatis 修改操作运行过程细节的重要的步骤。下方这个表格描述了这些设置项、含义和默认值。
设置项 | 描述 | 允许值 | 默认值 |
cacheEnabled | 对在此配置文件下的所有cache 进行全局性开/关设置。 | true | false | true |
lazyLoadingEnabled | 全局性设置懒加载。如果设为‘false',则所有相关联的都会被初始化加载。 | true | false | true |
aggressiveLazyLoading | 当设置为‘true'的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 | true | false | true |
multipleResultSetsEnabled | 允许和不允许单条语句返回多个数据集(取决于驱动需求) | true | false | true |
useColumnLabel | 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。 | true | false | true |
useGeneratedKeys | 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 | true | false | false |
autoMappingBehavior | 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。 | NONE, PARTIAL, FULL | PARTIAL |
defaultExecutorType | 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。 | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时 | 正整数 | Not Set (null) |
例如:
<settings>
<setting name="cacheEnabled" value="true" />
<setting name="lazyLoadingEnabled" value="true" />
<setting name="multipleResultSetsEnabled" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="useGeneratedKeys" value="false" />
<setting name="enhancementEnabled" value="false" />
<setting name="defaultExecutorType" value="SIMPLE" />
</settings>
2.3 typeAliases类型别名
类型别名是Java 类型的简称。
它仅仅只是关联到XML 配置,简写冗长的JAVA 类名。例如:
<typeAliases>
<typeAlias alias="UserEntity" type="com.manager.data.model.UserEntity" />
<typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity" />
<typeAlias alias="ClassEntity" type="com.manager.data.model.ClassEntity" />
</typeAliases>
使用这个配置,“StudentEntity”就能在任何地方代替“com.manager.data.model.StudentEntity”被使用。
对于普通的Java类型,有许多内建的类型别名。它们都是大小写不敏感的,由于重载的名字,要注意原生类型的特殊处理。
别名 | 映射的类型 |
_byte | byte |
_long | long |
_short | short |
_int | int |
_integer | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
integer | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
bigdecimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
iterator | Iterator |
2.4 typeHandlers类型句柄
无论是MyBatis在预处理语句中设置一个参数,还是从结果集中取出一个值时,类型处理器被用来将获取的值以合适的方式转换成Java类型。下面这个表格描述了默认的类型处理器。
类型处理器 | Java类型 | JDBC类型 |
BooleanTypeHandler | Boolean,boolean | 任何兼容的布尔值 |
ByteTypeHandler | Byte,byte | 任何兼容的数字或字节类型 |
ShortTypeHandler | Short,short | 任何兼容的数字或短整型 |
IntegerTypeHandler | Integer,int | 任何兼容的数字和整型 |
LongTypeHandler | Long,long | 任何兼容的数字或长整型 |
FloatTypeHandler | Float,float | 任何兼容的数字或单精度浮点型 |
DoubleTypeHandler | Double,double | 任何兼容的数字或双精度浮点型 |
BigDecimalTypeHandler | BigDecimal | 任何兼容的数字或十进制小数类型 |
StringTypeHandler | String | CHAR和VARCHAR类型 |
ClobTypeHandler | String | CLOB和LONGVARCHAR类型 |
NStringTypeHandler | String | NVARCHAR和NCHAR类型 |
NClobTypeHandler | String | NCLOB类型 |
ByteArrayTypeHandler | byte[] | 任何兼容的字节流类型 |
BlobTypeHandler | byte[] | BLOB和LONGVARBINARY类型 |
DateTypeHandler | Date(java.util) | TIMESTAMP类型 |
DateOnlyTypeHandler | Date(java.util) | DATE类型 |
TimeOnlyTypeHandler | Date(java.util) | TIME类型 |
SqlTimestampTypeHandler | Timestamp(java.sql) | TIMESTAMP类型 |
SqlDateTypeHandler | Date(java.sql) | DATE类型 |
SqlTimeTypeHandler | Time(java.sql) | TIME类型 |
ObjectTypeHandler | Any | 其他或未指定类型 |
EnumTypeHandler | Enumeration类型 | VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引)。 |
你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。要这样做的话,简单实现TypeHandler接口(org.mybatis.type),然后映射新的类型处理器类到Java类型,还有可选的一个JDBC类型。然后再typeHandlers中添加这个类型处理器。
新定义的类型处理器将会覆盖已经存在的处理Java的String类型属性和VARCHAR参数及结果的类型处理器。要注意MyBatis不会审视数据库元信息来决定使用哪种类型,所以你必须在参数和结果映射中指定那是VARCHAR类型的字段,来绑定到正确的类型处理器上。这是因为MyBatis直到语句被执行都不知道数据类型的这个现实导致的。
public class LimingStringTypeHandler implements TypeHandler {
@Override
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
System.out.println("setParameter - parameter: " + ((String) parameter) + ", jdbcType: " + jdbcType.TYPE_CODE);
ps.setString(i, ((String) parameter));
}
@Override
public Object getResult(ResultSet rs, String columnName) throws SQLException {
System.out.println("getResult - columnName: " + columnName);
return rs.getString(columnName);
}
@Override
public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
System.out.println("getResult - columnIndex: " + columnIndex);
return cs.getString(columnIndex);
}
}
在配置文件的typeHandlers中添加typeHandler标签。
<typeHandlers>
<typeHandler javaType="String" jdbcType="VARCHAR" handler="liming.student.manager.type.LimingStringTypeHandler"/>
</typeHandlers>
2.5 ObjectFactory对象工厂
每次MyBatis 为结果对象创建一个新实例,都会用到ObjectFactory。默认的ObjectFactory 与使用目标类的构造函数创建一个实例毫无区别,如果有已经映射的参数,那也可能使用带参数的构造函数。
如果你重写ObjectFactory 的默认操作,你可以通过继承org.apache.ibatis.reflection.factory.DefaultObjectFactory创建一下你自己的。
ObjectFactory接口很简单。它包含两个创建用的方法,一个是处理默认构造方法的,另外一个是处理带参数构造方法的。最终,setProperties方法可以被用来配置ObjectFactory。在初始化你的ObjectFactory实例后,objectFactory元素体中定义的属性会被传递给setProperties方法。
public class LimingObjectFactory extends DefaultObjectFactory {
private static final long serialVersionUID = -399284318168302833L;
@Override
public Object create(Class type) {
return super.create(type);
}
@Override
public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
System.out.println("create - type: " + type.toString());
return super.create(type, constructorArgTypes, constructorArgs);
}
@Override
public void setProperties(Properties properties) {
System.out.println("setProperties - properties: " + properties.toString() + ", someProperty: " + properties.getProperty("someProperty"));
super.setProperties(properties);
}
}
配置文件中添加objectFactory标签
<objectFactory type="liming.student.manager.configuration.LimingObjectFactory">
<property name="someProperty" value="100"/>
</objectFactory>
2.6 plugins插件
MyBatis允许你在某一点拦截已映射语句执行的调用。默认情况下,MyBatis允许使用插件来拦截方法调用:
Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler(getParameterObject, setParameters)
ResultSetHandler(handleResultSets, handleOutputParameters)
StatementHandler(prepare, parameterize, batch, update, query)
这些类中方法的详情可以通过查看每个方法的签名来发现,而且它们的源代码在MyBatis的发行包中有。你应该理解你覆盖方法的行为,假设你所做的要比监视调用要多。如果你尝试修改或覆盖一个给定的方法,你可能会打破MyBatis的核心。这是低层次的类和方法,要谨慎使用插件。
使用插件是它们提供的非常简单的力量。简单实现 * 接口,要确定你想拦截的指定签名。
2.7 environments环境
MyBatis 可以配置多个环境。这可以帮助你SQL 映射对应多种数据库等。
2.8 mappers映射器
这里是告诉MyBatis 去哪寻找映射SQL 的语句。可以使用类路径中的资源引用,或者使用字符,输入确切的URL 引用。
例如:
<mappers>
<mapper resource="com/manager/data/maps/UserMapper.xml" />
<mapper resource="com/manager/data/maps/StudentMapper.xml" />
<mapper resource="com/manager/data/maps/ClassMapper.xml" />
</mappers>
猜你喜欢
- 来到杭州,迅速租了房子,扫了日常用品。再非专业地提前体验一下与工作有那么一点点点点点相关的UED(用户体验设计)。良好的用户体验是一种非必须
- 在一次ASP程序中不能正常连接MSSQL出现出错信息如下:以下为引用的内容:HTTP/1.1 200 OK S
- 前言在 PyQt 中可以使用很多方式实现照片查看器,最朴素的做法就是重写 QWidget 的 paintEve
- 前言利用Django开发网站,可以设计出非常优美的url规则,如果url的匹配规则(包含正则表达式)组织得比较好,view的结构就会比较清晰
- 实现一个支持动态扩容的数组并完成其增删改查#通过python实现动态数组"""数组特点: 占用一段
- 前言pandas 默认整合XlsxWriter驱动,自动化处理excel操作,提供公式、设置单元格格式、可视化分析图片等操作XlsxWrit
- 数据库:30万条,有ID列但无主键,在要搜索的“分类”字段上建有非聚集索引过程T-SQL: /* 用户自定义函数:执行时间在115
- 每个 ndarray 都有一个关联的数据类型 (dtype) 对象。这个数据类型对象(dtype)告诉我们数组的布局。这意味着它为我们提供了
- Python 语句语句是 Python 解释器解析和处理的基本指令单元。通常解释器按顺序一个接一个的执行语句。在 REPL 会话中,语句在输
- Decode函数的语法结构如下:decode (expression, search_1, result_1)decode (express
- 本文实例为大家分享了python实现微信消息防撤回的具体代码,供大家参考,具体内容如下使用了sqlite3保存数据,当有人撤回消息时取出数据
- Python 中的运算符什么是运算符?举个简单的例子 4 +5 = 9 。 例子中,4 和 5 被称为操作数,"+" 称
- 1、关于参数的区别实例方法:定义实例方法是最少有一个形参 ---> 实例对象,通常用 self类方法:定义类方法的时候最少有一个形参
- pygal的安装大家可以参阅:pip和pygal的安装实例教程线图:import pygalline_chart = pygal.Line(
- 这篇文章主要介绍了Python手绘可视化工具cutecharts使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为Tru
- 导语🎁哈喽!哈喽!我是木木子😎,今日游戏更新——超级玛丽华丽上线🎊啦!“超级玛丽”有多少人还记得这款经典游戏?对于90、00后应该不大熟悉,
- 如下所示:stopword = ''str = ''for line in iter(raw_input,
- 代码:import tensorflow as tfsess = tf.Session()check_point_path = 'v
- 安装anaconda 是自动集成的如果导入不存在,直接pippip install tqmd参数#参数介绍iterable=None,des