设为首页 收藏本站
查看: 1030|回复: 0

[经验分享] (七)配置及用法之MyBatis

[复制链接]

尚未签到

发表于 2016-11-26 05:18:21 | 显示全部楼层 |阅读模式
现在介绍一个算是半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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305525-1-1.html 上篇帖子: Mybatis返回Map的一种实现 下篇帖子: spring+mybatis+atomikos 实现JTA事务
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表