Java+Spring+MySql环境中安装和配置MyBatis的教程
1.MyBatis简介与配置MyBatis+Spring+MySql 1.1MyBatis简介 1.2.2建立MySql数据库 /* 建立数据库 */ 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.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创建数据访问接口 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 <?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配置文件 <?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 的配置文件 <!-- 导入属性配置文件 --> <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,使用注解: @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 @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的主配置文件 <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>
例如: <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类型别名 <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”被使用。
2.4 typeHandlers类型句柄
你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。要这样做的话,简单实现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对象工厂 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允许使用插件来拦截方法调用:
这些类中方法的详情可以通过查看每个方法的签名来发现,而且它们的源代码在MyBatis的发行包中有。你应该理解你覆盖方法的行为,假设你所做的要比监视调用要多。如果你尝试修改或覆盖一个给定的方法,你可能会打破MyBatis的核心。这是低层次的类和方法,要谨慎使用插件。 2.7 environments环境 2.8 mappers映射器 <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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |