一、基于XMl的Mybatis开发
1、添加mybatis的启动器
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
2、在application.properties中添加相关配置
# 配置 mybatis-config.xml 路路径,mybatis-config.xml 中配置 MyBatis 基础属性
mybatis.config-location=classpath:mybatis/mybatis-config.xml
# 配置 mapper映射文件的位置
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3、定义DAO
public interface *DAO{
List<*Entity> findUserById(int id);
}
4、书写mapper.xml映射文件
<mapper namespace="cn.dao.*DAO" >
<sql id="*_column_name" >
id, *Name, passWord, nick_*
</sql>
<select id="find*ById" parameterType="int"
resultType="cn.entity.*Entity" >
SELECT
<include refid="*_column_name" />
FROM *
WHERE id = #{id}
</select>
</mapper>
5、使用@MapperScan注解进行DAO扫描
@SpringBootApplication
@MapperScan("cn.*.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
二、基于注解的Mybatis开发
1.添加mybatis的启动器
2.application.properties相关配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3、书写DAO
public interface *DAO{
// #{}取出参数值
@Delete("DELETE FROM * WHERE id = #{id}")
void delete(int id);
//@Param 指定参数名
@Select("SELECT ** FROM * WHERE *_gender = #{gender}")
List<*> getListByUserSex(@Param("gender") String userGender);
//使用map传递参数
@Select("SELECT ** FROM * WHERE *_name=#{username}"+
"AND password = #{password}")
* get*ByNameAndPassword(Map<String, Object> map);
//使用实体对象
@Insert("INSERT INTO *(*_name,passWord,*_gender)"+
"VALUES(#{*Name}, #{passWord}, #{*Gender})")
void insert(* *);
@Update("UPDATE * SET *Name=#{*Name} WHERE id =#{id}")
void update(* *);
}
扫描对应的DAO
@SpringBootApplication
@MapperScan("cn.*.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4、@Results 和 @Result 注解
这两个注解配合来使用,主要作用是将数据库中查询到的数值转化为具体的字段,修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
@Select("SELECT * FROM *")
@Results({
@Result(property = "*Name", column = "*_name", ),
@Result(property = "*Gender", column = "*_gender")
})
List<*> getAllUser();