总结
hibernate 和 mybatis 的区别
hibernate的特点是所有的sql都用java代码生成,不用跳出程序去(看)sql,发展到最顶端就是Spring data jpa了。
mybatis初期使用比较麻烦,需要各种配置文件、实体类、dao层映射关联、还有一大堆其他配置,初期开发了generator可以根据表结果自动生成实体类、配置文件和dao层代码;后期进行了大量优化可以使用注解,自动管理dao层和配置文件。发展到最顶端就是 mybatis-Spring-boot-starter 可以完全注解不用配置文件。
使用 mybatis-Spring-boot-starter有两种方法
- 无配置文件注解版
1 添加pom文件;
2 添加application.propertis相关配置;在启动类中添加mapper包扫描
3 开发mapper;
4 使用; - xml版
1 配置,添加pom文件、application.properties(指定配置文件和映射文件的位置),mybatis-config.xml(配置一些mybatis的基础参数)
2 添加类的映射文件(UserMapper)
3 编写dao层代码(这里只需要写dao层接口,不用写实现)
4 使用
如何选择两种方法
注解适合快速开发,比如微服务器;
xml适合大型项目
mybatis-Spring-boot-starter
首先,引入mybatis-Spring-boot-starter 的pom文件
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version>
</dependency>
接下来,介绍两种开发模式:
无配置文件注解版
就是一切使用注解搞定
1 添加相关maven文件
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>
</dependencies>
2 application.properties 添加相关配置
mybatis.type-aliases-package=com.neo.entityspring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
springboot会自动加载Spring.datasource.XX相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory 会自动注入到Mapper中。不用管,直接拿来用。
在启动类中添加mapper包扫描(“com.neo.mapper”)
@SpringBootApplication
@MapperScan("com.neo.mapper") //添加mapper包扫描
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
也可以直接在Mapper类上添加主角@Mapper
,建议使用上面那种,不然每个Mapper都要加注解。
3 开发Mapper
这是最关键的一步, sql生产都在这里
public interface UserMapper {@Select("SELECT * FROM users")@Results({@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),@Result(property = "nickName", column = "nick_name") }) //为更接近生产,user_sex、nick_name 两个属性在数据库加了下划线和实体类属性名不一致,另外user_sex使用了枚举。List<UserEntity> getAll();@Select("SELECT * FROM users WHERE id = #{id}")@Results({@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),@Result(property = "nickName", column = "nick_name")})UserEntity getOne(Long id);@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")void insert(UserEntity user);@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")void update(UserEntity user);@Delete("DELETE FROM users WHERE id =#{id}")void delete(Long id);}
为更接近生产,user_sex、nick_name 两个属性在数据库加了下划线和实体类属性名不一致,另外user_sex使用了枚举。
@Select 是查询类的注解,所有的查询均使用这个。
@Result 修饰返回的结果集,关联实体类属性和数据库字段——一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
@Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
@Update 负责修改,也可以传入对象。
@Delete 负责删除
了解更多属性参考这里
以上是简单的查询,下面的博客介绍复杂查询
连表查询:SpringBoot使用Mybatis注解进行一对多和多对多查询
分页查询:SpringBoot集成MyBatis的分页插件PageHelper(PageHelper使用了拦截器的原理实现分页);Mybatis使用pageHelper分页插件原理
注意,使用#符号和$符号的不同:
#{}:占位符号,好处防止sql注入
${}:sql拼接符号
动态sql是mybatis的强大特性之一,也是它优于其他ORM框架的一个重要原因。mybatis在对sql语句进行预编译之前,会对sql进行动态解析,解析为一个BoundSql 对象,也是在此处对sql 进行处理的。在动态SQL解析阶段,#{}和 ${}会有不同的表现。
用法:
- 能用#{}的地方就用#{}
首先是性能考虑,相同编译的sql可以重复利用。,其次,使用 ${} 在编译之前被变量替换,会存在sql注入问题;
sql注入问题:
select * from ${tablename} where name = #{name};
//若tablename 为 user; delete user; – ,在动态解析阶段,预编译之前 sql将变为
select * from user;delect user; – where name = ?;- 表名作为变量时,必须使用${}
这是因为,表名是字符串,使用sql占位符替换字符串会带上单引号‘’,这会导致sql语法错误,例如:
这里有一篇很好的文章解释了这个问题:【#和$】MyBatis中 #和 $的区别
4 使用
上面散步就基本完成了dao层开发,使用的时候当作普通的类注入就可以了
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper UserMapper;@Testpublic void testInsert() throws Exception {UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));Assert.assertEquals(3, UserMapper.getAll().size());}@Testpublic void testQuery() throws Exception {List<UserEntity> users = UserMapper.getAll();System.out.println(users.toString());}@Testpublic void testUpdate() throws Exception {UserEntity user = UserMapper.getOne(3l);System.out.println(user.toString());user.setNickName("neo");UserMapper.update(user);Assert.assertTrue(("neo".equals(UserMapper.getOne(3l).getNickName())));}
}
源码中controler层有完整的增删改查,这里就不贴了
源码在这里spring-boot-mybatis-annotation
极简xml版本
极简xml 版本保持映射文件的老传统,优化主要体现在不需要实现dao的实现层,系统会自动根据方法名在映射文件中找对应的sql。
1 配置
pom文件和上个版本一样,只是application.properties新增以下配置
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
指定了mybatis 基础配置文件和实体类映射文件的地址。
mybatis-config.xml配置
<configuration><typeAliases><typeAlias alias="Integer" type="java.lang.Integer" /><typeAlias alias="Long" type="java.lang.Long" /><typeAlias alias="HashMap" type="java.util.HashMap" /><typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" /><typeAlias alias="ArrayList" type="java.util.ArrayList" /><typeAlias alias="LinkedList" type="java.util.LinkedList" /></typeAliases>
</configuration>
这里也可以添加一些mybatis基础的配置
2 添加User的配置文件
<mapper namespace="com.neo.mapper.UserMapper" ><resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" ><id column="id" property="id" jdbcType="BIGINT" /><result column="userName" property="userName" jdbcType="VARCHAR" /><result column="passWord" property="passWord" jdbcType="VARCHAR" /><result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/><result column="nick_name" property="nickName" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, userName, passWord, user_sex, nick_name</sql><select id="getAll" resultMap="BaseResultMap" >SELECT <include refid="Base_Column_List" />FROM users</select><select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >SELECT <include refid="Base_Column_List" />FROM usersWHERE id = #{id}</select><insert id="insert" parameterType="com.neo.entity.UserEntity" >INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})</insert><update id="update" parameterType="com.neo.entity.UserEntity" >UPDATE users SET <if test="userName != null">userName = #{userName},</if> <!-- 条件 --><if test="passWord != null">passWord = #{passWord},</if>nick_name = #{nickName}WHERE id = #{id}</update><delete id="delete" parameterType="java.lang.Long" >DELETE FROMusers WHERE id =#{id}</delete>
</mapper>
其实就是把上个版本中mapper的sql搬到了这里
3 编写dao层代码
public interface UserMapper {List<UserEntity> getAll();UserEntity getOne(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);}
对比上一步这里全部只剩下接口方法。
4 使用
使用和上个版本没有区别。
代码:xml配置版本
如何选择两种模式
两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务器模式,一个微服务就会对应一个自己的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。
老传统模式比较适合大型项目,可以灵活的动态生成sql,方便调整sql,也有痛痛快快,洋洋洒洒写sql的感觉。
完整代码地址
作者:纯洁的微笑
出处:http://www.ityouknow.com/
版权所有,欢迎保留原文链接进行转载:)