1. 功能
连接数据库,进行增删改查操作
2. 类结构图
3. 实现
#实体UserEntity
package com.jihite.entity;import com.jihite.enums.SexEnum;public class UserEntity { private Long id; private String name; private String passwd; private SexEnum sex; public UserEntity() { } public UserEntity(String name, String passwd, SexEnum sex) { this.id = id; this.name = name; this.passwd = passwd; this.sex = sex; } public long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public SexEnum getSex() { return sex; } public void setSex(SexEnum sex) { this.sex = sex; } @Override public String toString() { return String.format("+++++ id:%s, name:%s, passwd:%s, sex:%s\n", id, name, passwd, sex); }}
#枚举 SexEnum
package com.jihite.enums;public enum SexEnum { MAN, WOMAN}
#接口UserMapper
package com.jihite.mapper;import com.jihite.entity.UserEntity;import com.jihite.enums.SexEnum;import org.apache.ibatis.annotations.*;import org.springframework.stereotype.Component;import java.util.List;@Componentpublic interface UserMapper { @Select("select * from users") @Results({ @Result(property = "name", column = "userName"), @Result(property = "passwd", column = "passWord"), @Result(property = "sex", column = "user_sex", javaType = SexEnum.class), }) ListgetAll(); @Select("SELECT * FROM users WHERE id=#{id}") @Results({ @Result(property = "name", column = "userName"), @Result(property = "passwd", column = "passWord"), @Result(property = "sex", column = "user_sex", javaType = SexEnum.class), }) UserEntity getOne(Long id); @Insert("INSERT INTO users(userName, passWord, user_sex) VALUES(#{name}, #{passwd}, #{sex})") void insert(UserEntity user); @Update("UPDATE users SET userName=#{name}, passWord=#{passwd} where id=#{id}") void update(UserEntity user); @Delete("DELETE from users where id=#{id}") void delete(Long id);}
#Application
package com.jihite;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.jihite.mapper")public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
#datasource
mybatis.type-aliases-package=com.jihitespring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8spring.datasource.username = usernamespring.datasource.password = passwd
4. 注释
4.1 加载datasource
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中
我们一切都不用管,直接拿起来使用就行
4.2 对mapper包进行扫描
方法一:在启动类中添加对mapper包扫描@MapperScan
方法二:直接在Mapper类(UserMapper)上面添加注解@Mapper
建议使用方法一,不然每个mapper加个注解也挺麻烦的
4.3 @Result
@Result(property = "name", column = "userName")
写明了实体字段名(name)和数据库字段(userName)的对应关系