MyBatis小结
Mybatis工具类(加了锁)
package online.hengtian.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
private static final Class CLASS_LOCK=MybatisUtil.class;
public static SqlSessionFactory initSqlSessionFactory(){
String resource="mybatis.cfg.xml";
InputStream in=null;
try {
in= Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
synchronized (CLASS_LOCK) {
if(sqlSessionFactory==null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sqlSessionFactory;
}
public static SqlSession getSqlSession(){
if(sqlSessionFactory==null) initSqlSessionFactory();
return sqlSessionFactory.openSession();
}
}
Mybatis配置
jdbc.properties配置文件
#数据库配置文件jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/store_db?serverTimezone=Asia/Shanghai
username=root
password=HengTian0.0
mybatis.cfg.xml配置文件
<?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>
<!--加载的jdbc配置文件-->
<properties resource="jdbc.properties">
</properties>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<typeAliases>
<package name="online.hengtian.domain"></package>
</typeAliases>
<!-- Continue going here -->
<!--dev就是development的意思-->
<environments default="dev">
<environment id="dev">
<!--事务管理器-->
<transactionManager type="JDBC">
<property name="autoCommit" value="false"></property>
</transactionManager>
<!--配置数据源-->
<dataSource type="UNPOOLED">
<property name="driver" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</dataSource>
</environment>
</environments>
<!--在此处添加映射的mapper文件-->
<mappers>
<!--Demo-->
<mapper resource="online.hengtian.mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.online.hengtian.mapper.UserMapper=DEBUG
log4j.logger.online.hengtian.mapper.CategoryMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
将配置文件放在src的resources中
mybatis映射器
mybatis多个参数传递
-
使用Map传递参数
<select id="findByMap" parameterType="map" resultMap="roleMap"> select id,name,hobby from man where name like concat('%',#{name},'%') and hobby like concat('%',#{hobby},'%') </select>
Map<String,String> paramsMap=new HashMap<String,String>(); paramsMap.put("name","me"); paramsMap.put("hobby","base"); manMapper.findByMap(paramsMap);
-
使用注解的方式传递参数
manMapper.findByNameAndHobby(@Param("name") String name,@Param("hobby") String hobby);
-
使用JavaBean传递参数
定义一个要参数的JavaBean并实现其中的setter和getter方法,然后可以直接通过该JavaBean查询
public class ManParam{ String name; String hobby; public String getName(){ return name; } public String getHobby(){ return hobby; } public void setName(String name){ this.name=name; } public void setHobby(String hobby){ this.hobby=hobby; } }
//mapper中的接口 public List<Man> findByParams(ManParam params);
-
总结
- 应尽量避免用map传递参数,这样使得程序可读性变差,并难以维护
- 使用@Param注解传递参数时,受参数个数的影响,当参数的个数小于五个时,用注解的方法最佳,但是当参数大于五个时,用JavaBean更好,因为JavaBean的方式更加直观;多个参数会给调用带来麻烦
- 当参数个数大于5个时,建议使用JavaBean方式
Insert元素
主键回填和自定义
<!--自动插入主键-->
<insert id="insertMan" parameterType="man" useGeneratedKeys="true" keyProperty="id">
insert into man(name,hobby) values (#{name},#{hobby})
</insert>
<!--自定义生成主键
如果表中没有记录,就设置id=1,否则就取最大的id+2来设置新的主键
这时需要用到selectKey元素进行处理
-->
<insert id="insertMan" pararmeterType="man" useGenerateKeys="true" keyProperty="id">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select if(max(id) is null,1,max(id)+2) as newId from man
</selectKey>
insert into man(name,hobby) values (#{name},#{hobby})
</insert>
Sql元素
sql元素可以简化我们的sql语句,比如我们要重复使用几个sql的字段时,可以用sql元素来简化我们的程序
<sql id="columns">
#{man}.name,#{man}.hobby
</sql>
<select parameterType="long" id="getMan" resultType="ManWithoutId">
select <include refid="columns"/> from man where id=#{id}
</select>
<select parameterType="long" id="getMan" resultType="Man">
select
<include>
<!--相当于添加了一个#{man}.id-->
<property name="man" value="id"></property>
</include>
from man where id=#{id}
</select>