`
woaiyingyu123
  • 浏览: 69780 次
  • 性别: Icon_minigender_1
  • 来自: 广西
社区版块
存档分类
最新评论

(七)配置及用法之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的基本配置如下,更深层次的使用请参照文档,文档在文章开始处的地址有下载的。如果有什么错漏的请留言,共同学习,谢谢!
分享到:
评论

相关推荐

    mybatis慢SQL插件

    使用方法: 找到你springboot项目中的配置文件,增加如下配置即可 application.yml 配置如下: sql: slow-threshold: 100 或 application.properties 配置如下: sql.slow-threshold=100 参数解释:以上...

    eclipse配置mybatis generrator 插件 生成逆向工程

    eclipse配置 mybatis generrator 插件 生成逆向工程 mybatis generrator 配置文件

    全面学习Mybatis插件之Mybatis-Plus_Java框架视频教程

    使用原生的Mybatis编写持久层逻辑时,所需要的代码是比较繁琐的,需要定义Mapper接口和Mapper.xml文件,每一个方法都需要编写对应的sql语句,会存在很多大量的重复工作,使用MP之后,对通用的方法做了高度的抽取,...

    MyBatis基本使用总结

    MyBatis基本使用总结 Mybatis 的核心配置文件于实体类的映射文件,mapper 代理动态代理的调用方法。

    lanlan2017#JavaReadingNotes#9.2 深入MyBatis的配置文件 9.2.1 MyBatis的配置文

    - 第9章 MyBatis的基本用法- 9.2 深入MyBatis的配置文件9.2 深入MyBatis的配置文件MyBatis的持久化操作离不开SqlSessi

    springmybatis

    mybatis实战教程mybatis in action之七实现mybatis分页源码下载 mybatis实战教程mybatis in action之八mybatis 动态sql语句 mybatis实战教程mybatis in action之九mybatis 代码生成工具的使用 mybatis ...

    mybatis在非spring环境下如何使用

    一般使用mybatis的环境,大多都是别人已经配置好的。直接用就好了,如何自己搭建呢?其实很简单。看官方的文档就可以解决了。主要为了学习mybatis最基础的配置。我文章中的方法不基于spring,一般很少会在真实项目中...

    Mybatis.PDF

    供了丰富的示例,通过自下而上的方法使读者更好地理解和掌握 MyBatis 的高级用法,同时针对 MyBatis 的代码生成器提供了详细的配置介绍。此外,本书还提供了缓存配置、插件开发、 Spring Spring Boot 成的详细内容...

    MyBatis Generator + PostgreSQL 逆向工程单独使用包及使用说明.rar

    关于逆向工程自动生成dao层代码的功能,网上很多介绍的都是mysql版本的,而且介绍的都是在开发环境idea或eclipse中怎么使用,这里整理的是PostgerSQL版本的,而且是单独使用的方法(附jar包,修配置文件直接可以使用...

    springboot整合redis、mybatis以及redis和mybatis的联合使用

    springboot集成redis、mybatis 1、集成redis 2、集成mybatis 3、自定义redis KEY生成器/CacheManager来管理redis... 方式一:redis原生方法工具类(RedisService)+redis+mybatis 方式二:CacheManager+redis+mybatis

    MyBatis_Generator_1.3.3

    如果你必须在一个旧版本的MyBatis运行,设置在配置属性“useLegacyBuilder”为“true”。 问题#11日 - Maven插件现在记录到日志行家(感谢保罗克劳斯) 问题#4 - Generator现在将抛出一个警告,如果任何列解析为一...

    springboot集成mybatis的两种使用方式

    资源里面包含两个项目,是springboot集成mybatis的两种方式,一个项目是使用老的xml的配置方式,一个是使用注解的方式。

    tidb(mysql5.7) springboot mybatis-plus

    java Springboot开发必备环境 : 推荐1: 统一参数校验,自定义异常提醒,统一日志,统一响应返回,统一异常处理 。...mybatis-plus 采用最新的生成代码工具 推荐3: 将多个基础功能整理后,并用单元测试验证。

    使用IDEA配置Maven + SpringMVC + Mybatis 【一步一步踩坑详细配置完成】SSM 框架

    初学,想使用Maven配置一个SpringMVC的开发环境,照着网上的各种图文解说,配置了好久都没成功,有些写的不够详细,有些只有写一半,走了不少弯弯绕绕,踩了不少的坑,此文将正确配置成功的步骤全部记录下来。...

    mybatis generator Java类方法生成

    mybatis generator Java类方法生成方法。附件是源码,可以直接运行,属于maven工程。 使用依赖: &lt;groupId&gt;mysql &lt;artifactId&gt;mysql-connector-java &lt;version&gt;5.1.45 &lt;!-- ...

    MyBatis从入门到精通__刘增辉电子工业出版社

    针对MyBatis高级映射、存储过程和类型处理器提供了丰富的示例,通过自下而上的方法使读者更好地理解和掌握MyBatis的高级用法,同时针对MyBatis的代码生成器提供了详细的配置介绍。此外,本书还提供了缓存配置、插件...

    Mybatis分页插件PageHelper配置及使用方法详解

    主要介绍了Mybatis分页插件PageHelper配置及使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Mybatis读写分离 mysql数据库 Druid连接池

    Mybatis读写分离,支持n多的从库,简单的负载均衡。数据库是mysql,采用druid连接池。 读写分离采用插件的形式实现的,优点是不需要写源注解,不需要写分开的Mapper.xml。...注意:没有使用Spring,只用到了Mybatis。

    一个不需要任何配置就可以直接使用的通用 MyBatis Mapper,通过简单的学习就可以直接在项目中使用

    开箱即用,无需任何配置,继承基类 Mapper 即可获得大量通用方法; 随心所欲,通过复制粘贴的方式可以组建自己的基类 Mapper; 全面贴心,提供 Service 层的封装方便业务使用和理解 Mapper; 简单直观,提供 ...

    MyBatis 从入门到精通

    针对 MyBatis 高级映射、存储过程和类型处理器提供了丰富的示例,通过自下而上的方法使读者更好地理解和掌握MyBatis 的高级用法,同时针对 MyBatis 的代码生成器提供了详细的配置介绍。此外,本书还提供了缓存配置、...

Global site tag (gtag.js) - Google Analytics