SpringBoot集成Mybatis

SpringBoot集成Mybatis


application.yml配置文件

spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?characterEncoding=utf8&serverTimezone=UTC

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.shanghuo.bean
  configuration:
    map-underscore-to-camel-case: true	#转换数据库的下划线命名法为驼峰命名

mapper配置文件

文件所在目录位置:resources.mybatis.mapper.AdminMapper.xml


DOCTYPE mapper
		PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shanghuo.mapper.AdminMapper">
	
	<select id="findAll" resultType="com.shanghuo.bean.AdminUser" resultMap="adminMap">
    	
        select * from t_admin
  	select>

    
	<resultMap id="adminMap" type="com.shanghuo.bean.AdminUser">
		
		<id property="adminId" column="admin_id"/>
		
		<result property="adminName" column="admin_name"/>
		<result property="adminPassword" column="admin_password"/>
	resultMap>
mapper>

实体类:

文件名:AdminUser.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AdminUser implements Serializable {

    private int adminId;
    private String adminName;
    private String adminPassword;
}

mapper层:

文件名:AdminMapper.java

@Mapper	//此注解表示该接口类的实现类对象交给mybatis底层创建,然后交由Spring框架管理。!!!
@Repository
public interface AdminMapper {
    /**
     * 查询所有
     * @return
     */
    public List<AdminUser> findAll();
}

service层:

文件名:AdminService.java

public interface AdminService {
    public List<AdminUser> findAll();
}

文件名:AdminServiceImpl.java

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public List<AdminUser> findAll() {
        return adminMapper.findAll();
    }
}

controller层:

文件名:AdminController.java

@RestController
public class AdminController {

    @Autowired
    public AdminService adminService;

    @RequestMapping("/admin")
    public String testadmin(){
        List<AdminUser> list = adminService.findAll();
        System.out.println(list.toString());
        return list.toString();
    }

}

数据库表结构:

admin_id admin_name admin_password
1 shanghuo 123456
2 chengtianyou11 000000

你可能感兴趣的:(java,spring,mysql,mybatis)