mybatis

mybatis

mybatis ORM框架-对象关系映射
初始使用:applicationContext-dao.xml
创建数据源(不同数据连接池):

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="maxActive" value="100"/>
    <property name="maxIdle"  value="30"/>
    <property name="maxWait" value="500"/>
    <property name="defaultAutoCommit" value="true"/>
    <property name="connectionProperties">
        <value>charSet=utf-8</value>
    </property>
</bean>

连接源:创建sqlSessionFactory(创建连接会话工厂)

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- 自动扫描mapping.xml文件 
    <property name="mapperLocations" value="classpath:com/situ/mapper/**.xml"></property>
 -->
 </bean>

扫描生成实现类:(dao接口通过clib代理生成实现类)

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

数据库事务管理器+注解支持

<bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- enable transaction annotation support --> 
<tx:annotation-driven transaction-manager="transactionManager"/>

注解模式:
@select
@insert
@update
@delete
@Option 主要用来配置查询状态的(设置缓存时间,自增的主键值)不推荐使用
https://blog.csdn.net/sinat_32023305/article/details/80253107
@Options(useGeneratedKeys = true, keyProperty = “Id”) //新增时有效
public void insert(Type t); 将自动编号列返回到源对象的指定属性中
useGeneratedKeys 设置为"true"表明要 MyBatis 获取由数据库自动生成的主键
keyProperty="id"指定把获取到的主键值注入到 XXX(实体类) 的 id 属性。
@Options(useCache=true,flushCache=false,timeout=100000)
useCache = true表示本次查询结果被缓存以提高下次查询速度,flushCache = false表示下次查询时不刷新缓存,timeout = 10000表示查询结果缓存10000秒
@result 列指定映射
@Results(
id=“userMap”,
value={
@Result(column=“id”, property=“id”, id=true),
@Result(column=“user_name”, property=“userName”),
@Result(column="user_password ", property=“userPassword”),
@Result(column=“user_email”, property=“userEmail”),
@Result(column=“user_info”, property=“userInfo”),
@Result(column=“head_img”, property=“headImg”, jdbcType=JdbcType.BLOB),
@Result(column=“create_time”, property=“createTime”,jdbcType=JdbcType.TIMESTAMP)

})
@resultmap 上述results的使用@resultmap(“usermap”)


<select id="selectComment" parameterType="int" resultMap="CommentResult">  
    select * from t_Comment where id = #{id}  
</select>  
  
<select id="selectBlog" parameterType="int" resultType="Blog">  
    select * from t_Blog where id = #{id}  
</select> 

@MapKey 指定map集合结果的key列
@MapKey(“id”)
@ResultMap(“BaseResultMap”)
@Select(“select * from user where hotel_address = #{address};”)
Map<Long, User> getUserByAddress(@Param(“address”) String address);
@Param 方法参数指定为sql字段的
@Select(“select * from user where hotel_address = #{address};”)
List getUserByAddress(@Param(“address”) String address);

xml模式:(可与注解模式共用):解开注解

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
     自动扫描mapping.xml文件 ,注解模式关键
    <property name="mapperLocations" value="classpath:com/situ/mapper/**.xml"></property>
 </bean>

xml模式不能加@param(“where”)

创建xml文件

<?xml version="1.0" encoding="UTF-8" ?>



select * from type ${_parameter}

select * from type where id=#{id} insert into type(name) values(#{name}) 动态sql语句 select * from type where id=9 choose,when,otherwise(switch 分支处理) foreach(循环)一般都是循环添加:: trim 规格化sql where 后置是否添加 and 或 or set 前置是否添加 修改时的set

用法:
${} 符号的作用是直接进行字符串拼接 select* from book $(where),小心SQL注入
#{}替换预编译语句(PrepareStatement)中的占位符?,不支持拼接,自带防sql注入 select * from book where name=#{name}

数据库事务:
数据库事务管理器:

<bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- enable transaction annotation support --> 
<tx:annotation-driven transaction-manager="transactionManager"/>

@Transactional,使用注解https://www.cnblogs.com/younggun/p/3193800.html
事务处理类型
事物传播行为介绍:
@Transactional(propagation=Propagation.REQUIRED) 注解在 dao的方法
如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)
方法中多条sql执行,一条失败,全部回滚
@Transactional(propagation=Propagation.REQUIRED)
public void insert(Type t) {
dao.insert(new Type(12, “1212”));
dao.insert(new Type(12, “133”));
}
@Transactional(propagation=Propagation.NOT_SUPPORTED)
容器不为这个方法开启事务
@Transactional(propagation=Propagation.REQUIRES_NEW)
不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务
@Transactional(propagation=Propagation.MANDATORY)
必须在一个已有的事务中执行,否则抛出异常
@Transactional(propagation=Propagation.NEVER)
必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)
@Transactional(propagation=Propagation.SUPPORTS)
如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.

事物超时设置:
@Transactional(timeout=30) //默认是30秒

事务隔离级别:
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
读取未提交数据(会出现脏读, 不可重复读) 基本不使用
@Transactional(isolation = Isolation.READ_COMMITTED)
读取已提交数据(会出现不可重复读和幻读)
@Transactional(isolation = Isolation.REPEATABLE_READ)
可重复读(会出现幻读)
@Transactional(isolation = Isolation.SERIALIZABLE)
串行化

脏读 : 一个事务读取到另一事务未提交的更新数据
不可重复读 : 在同一事务中, 多次读取同一数据返回的结果有所不同, 换句话说,
后续读取可以读到另一事务已提交的更新数据. 相反, "可重复读"在同一事务中多次
读取数据时, 能够保证所读数据一样, 也就是后续读取不能读到另一事务已提交的更新数据
幻读 : 一个事务读到另一个事务已提交的insert数据

spring缓存:
设置:







<cache:annotation-driven mode=“proxy” />//启用注解形式的缓存处理

xmlns:p=“http://www.springframework.org/schema/p”
xmlns:cache=“http://www.springframework.org/schema/cache”

http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd

@Cacheable 如果有缓存就取缓存,否则查询数据库
@Select(“select * from type ${txt} ${limit}”)
@Cacheable(“myselect”)
public List select(@Param(“txt”) String txt,@Param(“limit”) String limit);
@CacheEvict 清除指定缓存
@Insert(“insert into type (name) values(#{name})”)
@CacheEvict(value=“myselect”,allEntries=true)
public void insert(Type t);
@CachePut 每次都查数据库,放入缓存(不检验之前的缓存状况)11

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值