果果、 发表于 2016-11-26 05:18:21

(七)配置及用法之MyBatis

现在介绍一个算是半ORM框架的配置,那就是Mybatis。介绍mybatis的时候,我不想和Hibernate有过多的牵扯,虽然是有ORM的性质,但是还是分清楚点,以免混乱。。在这里,暂且不谈和Spring等框架的整合。下载Mybatis可以去http://code.google.com/p/mybatis/。本文中的一些标签内使用了类型别名,映射别名等,请参照上下文对比,积极尝试!
目前用到的包:asm-3.1.jar、cglib-2.2.jar、commons-logging-1.1.1.jar、log4j-1.2.13.jar、mybatis-3.0.5.jar、mybatis-3.0.5-javadoc.jar、mybatis-3.0.5-sources.jar、slf4j-api-1.5.8.jar、slf4j-log4j12-1.5.8.jar、mysql-connector-java-5.0.5-bin.jar
(1)使用到的持久化Bean:

public class Student {
private Integer uid;
private String studentName;
private List<Score> score;//关联映射。
//getter and setter 略
}
public class Score {
private Integer sid;
private String scoreName;
private Student student;//关联映射
//getter and setter 略
}

(1)mysql.properties的配置(设置具体数据源信息):
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybaties
username=root
password=123

(2)mysql-config.xml的配置:(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>
//各标签的顺序一般是:properties,settings,typeAliases,typeHandlers,objectFactory,objectWrapperFactory,plugins,environments,mappers,详细用法参考文档,这里做简单介绍而已!
<properties resource="mysql.properties" />//通过这个配置,可以把数据源的属性定义放在资源文件里,实现动态配置
<!-- 设置类型别名,可把全路径名进行自定义简化,方便以后引用-->
<typeAliases>
<typeAlias type="com.lrl.entity.Student" alias="StudentEntity" />
<typeAlias type="com.lrl.entity.Score" alias="ScoreEntity" />
</typeAliases>
<!-- 环境的配置 -->
<environments default="development">//默认环境id(使用的是以下定义的develpment)
<environment id="development">// 每个环境的id
<transactionManager type="JDBC" >
</transactionManager>
<!-- 数据源的定义-->
<dataSource type="POOLED">//UNPOOLED每次请求简单打开关闭(慢),POOLED避免创建新链接的链接认证时间(快),JNDI(和Spring等使用)
<property name="driver" value="${driver}" />//$引用资源文件里的属性
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- 配置实体类映射器Mapper -->
<mappers>
<mapper resource="com/lrl/entity/ScoreMapper.xml" />
</mappers>
</configuration>

(3)UserMapper.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要和映射器接口的全路径名相同(如果你打算使用接口的话) -->
<mapper namespace="com.lrl.dao.ScoreDao">
<!-- Score映射结果集 -->
<resultMap type="ScoreEntity" id="scoreResult">
<id property="sid" column="sid" />
<result property="scoreName" column="scoreName" />
<!--类型关联-->
<association property="student" column="uid" javaType="StudentEntity"
resultMap="studentResult" >//使用resultMap="studentResult"把两表属性联合在一起
<id property="uid" column="uid"/>
<result property="studentName" column="studentName"/>
</association>
//association也可以这样写:
<association property="student" column="uid" javaType="StudentEntity">//在里面添加属性,和使用resultMap="studentResult"性质一样
<id property="uid" column="uid"/>
<result property="studentName" column="studentName"/>
</association>
//association还可以这样写:
<association property="student" column="uid" javaType="StudentEntity"
select="findStudentById" >//会照成N+1问题,不大好
</association>
</resultMap>
<!-- Student映射结果集 -->
<resultMap type="StudentEntity" id="studentResult">
<id property="uid" column="uid" />
<result property="studentName" column="studentName" />
<collection property="score" ofType="ScoreEntity" >
<id property="sid" column="sid" />
<result property="scoreName" column="scoreName" />
</collection>
</resultMap>
//PS:resultMap里还有<constructor></constructor><discriminator></discriminator>等标签,详情请参照文档,这里只是简介而已!
<!-- 定义映射语句 ,id等价于方法名-->//resultType是返回类型,resultMap是映射结果集
<select id="findById" parameterType="Integer" resultType="ScoreEntity">
select
* from Score s where s.sid=#{sid}//#{}会自动匹配参数,暂且这里面的命名随意,但是并不是所有的都随意的。所以建议还是根据实体类里的命名把
</select>
<select id="findScoreToStudent" parameterType="Integer"
resultMap="scoreResult">
select * from Score s left outer join Student u on
s.uid=u.uid where s.sid=#{sid}//使用resultMap,可以进行表之间的级联关系,如果用resultType使用级联,则会空指针.
</select>
<select id="findStudentToScore" parameterType="Integer"
resultMap="studentResult">
select * from Student u left outer join Score s on
u.uid=s.uid where u.uid=#{uid}
</select>
<update id="updateByEntity" parameterType="ScoreEntity">
update Score s set s.scoreName=#{scoreName} where s.sid=#{sid}<!--
这里#{}里的是ScoreEntity的属性,不能随意命名!
-->
</update>
//还有<insert></insert>,<delete></delete>标签等。希望自己动手尝试使用这些标签。
</mapper>

(4)映射器接口:

public interface ScoreDao {
public Score findById(Integer sid);
public Score findScoreToStudent(Integer sid);
public void updateByEntity(Score score);
public Student findStudentToScore(Integer uid);
}
//如果觉得在UserMapper.xml(映射器)配置<select></select><update></update>等映射语句麻烦。那么可以在接口的定义方法上面使用注解@Select、@Insert等如:
@Select("select * from Score s where s.sid=#{sid}")
public Score findById(Integer sid);

(5)测试:

String resource = "mysql-config.xml";
Reader reader = Resources.getResourceAsReader(resource);//读取配置文件
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);//创建SqlSessionFactory,加载配置文件
SqlSession session = sessionFactory.openSession(true);// true为设置自动提交事务,如果不设置,那么要使用session.commit()提交事务,否则更新插入等无效。
ScoreDao scoreDao = session.getMapper(ScoreDao.class);//ScoreDao接口关联实际的映射器,注意映射器的namespace要和接口的全路径名一致。
Score score = scoreDao.findById(1);
System.out.println(score.getScoreName());//只对其一进行简单的测试

mybatis的基本配置如下,更深层次的使用请参照文档,文档在文章开始处的地址有下载的。如果有什么错漏的请留言,共同学习,谢谢!
页: [1]
查看完整版本: (七)配置及用法之MyBatis