-
实例需求:用户信息(用户名、别名、密码、性别、邮箱、创建时间),实现简单增删改查
-
技术要点:
- mybatis的xml型和注解型异同:
同:都是调用mapper接口来关联数据库;
异:xml型-mapper.xml文件通过mapper的namespace属性关联mapper接口,相应的sql脚本直接在mapper.xml文件实现;注解型-通过mapper接口对应的方法通过mybatis注解来关联和管理sql脚本。
- springboot单数据源配置:
注解型的,配置文件去除mybatis相关配置
spring.datasource.driverClassName:数据源驱动类
spring.datasource.url:数据源url
spring.datasource.username:用户名
spring.datasource.password:密码
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://192.168.32.128:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
- springboot与mybatis集成配置:
@MapperScan("com.lm.mapper")
使用@MapperScan来扫描注册mybatis数据库接口类
/**
* 应用启动
*
* @author liangming.deng
* @date 2017年6月20日
*
*/
@SpringBootApplication
@MapperScan("com.lm.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
- 使用相关的mybatis注解对Mapper接口进行开发:
/**
* mybatis中mapper接口
* @author liangming.deng
* @date 2017年6月21日
*
*/
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id=true,property="id",column="id"),
@Result(property="userName",column="userName"),
@Result(property="nickName",column="nickName"),
@Result(property="passWord",column="passWord"),
@Result(property="email",column="email"),
@Result(property="regTime",column="regTime"),
@Result(property="sexEnums",column="sex",javaType=SexEnums.class)})
List<UserEntity> getAll();
@Select("select * from user where id=#{id}")
@Results({
@Result(id=true,property="id",column="id"),
@Result(property="userName",column="userName"),
@Result(property="nickName",column="nickName"),
@Result(property="passWord",column="passWord"),
@Result(property="email",column="email"),
@Result(property="regTime",column="regTime"),
@Result(property="sexEnums",column="sex",javaType=SexEnums.class)})
UserEntity getUserById(Long id);
@Insert("INSERT INTO user(userName,nickName,passWord,email,regTime,sex) "
+ "VALUES(#{userName}, #{nickName}, #{passWord}, #{email}, #{regTime}, #{sex}) ")
void insert(UserEntity user);
@Update("UPDATE user SET userName=#{userName},nickName=#{nickName} where id=#{id}")
void update(UserEntity user);
@Delete("DELETE FROM user where id=#{id}")
void delete(Long id);
}
- 进行controller层的开发:注入相应的Mapper接口进行操作