您的位置:首页 > 其它

MyBatis

2015-08-31 10:57 274 查看
MyBatis 配置文件的配置:

1.需要配置事务和数据库管理
配置事务:JDBC|MANAGED->JDBC是自己管理,MANAGED 是交给容器去管理(IOC)
<transactionManager type="JDBC"></transactionManager>
配置数据源:POOLED|UNPOOLED|JNDI
<dataSource type="POOLED">


MyBatis代码:

/**
* SqlSessionFactory:是线程安全的。
* SqlSession : 非线程安全。
*/
public void test(){
String resource = "sqlMapConfig.xml";
//可以通过Resources 来获取对应的配置文件。
InputStream inputStream =
Resources.getResourceAsStream(resource);
SqlSessionFactory factory =
new SqlSessionFactoryBuilder().build(inputStream);
}


MyBaits的Mapper配置文件:

占位符:
<!-- 对于参数是一个对象类型的,其占位符的名字必须是对象对应的属性名才可以。 -->
<insert id="insert" parameterType="com.ronnie.mybatis.entities.Person">
INSERT INTO person(id,user_name,age,remark)
VALUES(#{id},#{name},#{age},#{remark})
</insert>

删除记录:
<!-- 删除多条[数组类型、集合(list)、map类型]
数组:  collection 属性为array
list集合: collection 属性为list -->
<delete id="deleteArray" parameterType="int">
DELETE FROM person
WHERE id IN
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>


/**
* 使用Map删除多条记录,而Map中的value必须是一个集合或者是数组才可以。
*/
@Test
public void deleteMap(){
SqlSession session = factory.openSession();
Map<String, Object> params = new HashMap<String, Object>();
int[] ids = {5,6};
params.put("ids", ids);
session.delete("com.ronnie.mybatis.mapper.deleteMap", params);
}
对应的配置文件为:


<!--parameterType属性为 map, collection的值为上述对应Map集合中的key值。 -->
<delete id="deleteMap" parameterType="map">
DELETE FROM person
WHERE id IN
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>


<!-- SQL 片段,其他的sql语句可以引用 -->
<sql id="cols">id,name,age</sql>
<!--在引用的时候使用<include> 标签来使用-->
<select id="findAllPerson" resultMap="personRM">
SELECT <include refid="cols"/> FROM person
</select>

**映射关系**
对一的关系映射:
<!--对一的关系映射,使用 <association>标签,其中的类型就是对应对象的全类名。
在使用<resultMap>时,会自动为其进行级联关系的赋值。只需要在<select> 标签的
【resultMap属性】设置为<resultMap>标签的id属性值即可。-->
<resultMap type="com.ronnie.mybatis.entities.Person" id="personExRM">
<id property="id" column="ID"/>
</resultMap>

<!-- 使用继承关系配置 【对一】的关系。即是一个person 包含一个personExtenstion -->
<resultMap type="com.ronnie.mybatis.entities.Person"
id="personExtensionRM" extends="personExRM">
<association property="personExtension"
javaType="com.ronnie.mybatis.entities.PersonExtension">
<!-- 和【结果集】进行匹配,而不是和数据表匹配。故只需要column的值和查询语句中的字段一样即可。 -->
<id property="id" column="INFO_ID"/>
<result property="department" column="DEPARTMENT"/>
</association>
</resultMap>

<!--对应的查询语句-->
<select id="findEx" resultMap="personExtensionRM" parameterType="map">
SELECT
p.id,p.user_name,p.age,p.remark,
i.id AS info_id,i.department,i.join_date
FROM
(SELECT id,user_name,age,remark FROM person) p
LEFT JOIN
(SELECT id,department,join_date FROM person_info) i
ON p.id = i.id
<where>
<if test="name!=null">AND user_name=#{name}</if>
</where>
</select>

对多的关系映射:
<!-- 配置【对多】关系,可以使用继承也可以都写在一个resuleMap 中。对多一般都是用List集合。
和对一的类似,使用的是<collection>标签,使用的是ofType 属性,该属性是指集合中元素的类型。 -->
<resultMap type="com.ronnie.mybatis.entities.Person" id="personInfoBookRM"
extends="personExtensionRM">
<collection property="books" ofType="com.ronnie.mybatis.entities.Book">
<id property="id" column="BOOK_ID"/>
<result property="bookName" column="BOOK_NAME"/>
</collection>
</resultMap>


generator插件的配置

<generatorConfiguration>
<!-- 配置属性文件。(里面可以包括连接数据库的信息....) -->
<properties resource="generatorConfig.properties"/>

<!--  指定mysql的驱动包的路径,千万别放中文路径下  -->
<classPathEntry location="E:\soft\java\Java-commons\mysql-connector-java-5.1.35.jar"/>

<!-- 配置数据源和生成代码的位置。 -->
<context id="ronnie">

<!-- 是否生成注释,true表示不生成。 -->
<commentGenerator>
<property name="suppressAllComments" value="${suppressAllComments}"/>
</commentGenerator>

<jdbcConnection driverClass="${driverClass}" connectionURL="${url}"
userId="${username}" password="${password}" />

<!-- 生成的实体类的位置默认是src下。 -->
<javaModelGenerator targetPackage="${modelTargetPackage}"
targetProject="${targetProject}" />

<!-- 生成映射文件的位置。默认也是src下。 -->
<sqlMapGenerator targetPackage="${mapperTargetPackage}" targetProject="${targetProject}" />

<!--生成的接口的位置,里面是一些方法的声明。可以直接拷贝使用。然后也自己定义自己需要的方法-->
<javaClientGenerator targetPackage="${clienttargetPackage}"
targetProject="${targetProject}" type="XMLMAPPER" />

<!-- 指定要为那些表生成代码,schema不需要写。 -->
<table schema="" tableName="person"></table>
</context>
</generatorConfiguration>
对有关系的表,生成的模型并没有关联上,需要自己手工的添加关联。。。


配置二级缓存

<!-- 使用二级缓存 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
还需要添加一个ehcache自带的配置文件。


传递字符串类型参数

只能使用_parameter
SELECT a.*,b.*
from datasix_c3_statistics_defect a,
(SELECT
SUM(fhardspot) AS fhardspotSum
FROM
datasix_c3_statistics_defect c
where
1 = 1
<if test="_parameter != null and _parameter != ''">
and date_format(c.create_time,"%Y-%m") = #{_parameter}
</if>
) b
WHERE
1 = 1
<if test="_parameter != null and _parameter != ''">
AND DATE_FORMAT(a.create_time,"%Y-%m") = #{_parameter}
</if>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: