spring boot与mabatis整合

通过年龄找人:
1.添加springboot需要用的东西,web,mysql,mybatis,jdbc
2.创建包controller,service,dao,domain,配置文件中添加mapper文件,再此包下创建一个映射文件
3.写代码,首先domain层


@Data
public class people {
    private String name;
    private Integer age;
}

service层:

public interface PeopleService {
    people findByage(Integer age);
}
@Service
public class PeopleServiceImpl implements PeopleService {
    @Autowired
    PeopleDao peopleDao;
    @Override
    public people findByage(Integer age) {
        return peopleDao.findByAge(age);
    }
}

dao层:

public interface PeopleDao {
    people findByAge(@Param("age") Integer age);
}

controller层:

@RestController
public class PeopleConroller {
    @Autowired
    PeopleService peopleService;

    @RequestMapping("/findPeople")
    public people findOnePeople( Integer age) {
        return peopleService.findByage(age);
    }
}

映射文件:


    


配置文件:

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mypeople?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=3041
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

## Mybatis 配置
mybatis.typeAliasesPackage=com.shuai.springmybatis.domain
mybatis.mapperLocations=classpath:mapper/*.xml

启动类:

@SpringBootApplication
@MapperScan("com.shuai.springmybatis.dao")
public class SpringMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringMybatisApplication.class, args);
    }

}

xml整合需要在配置文件里配置,还需要在启动类里面添加@mapperscan注解比较麻烦
使用注解开发,配置文件,启动类里面都不需要再配置了只需要添加一个@mapper


@Mapper
public interface PeopleDao {
    @Select("select * from people where age=#{age}")
    people findByAge(@Param("age") Integer age);
}

你可能感兴趣的:(spring boot与mabatis整合)