美文网首页
spring boot与mabatis整合

spring boot与mabatis整合

作者: 李霖神谷 | 来源:发表于2019-11-26 17:29 被阅读0次

通过年龄找人:
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);
    }
}

映射文件:

<mapper namespace="com.shuai.springmybatis.dao.PeopleDao">
    <select id="findByAge" resultType="people" parameterType="java.lang.Integer">
    select * from people where  age=#{age};
  </select>

</mapper>

配置文件:

## 数据源配置
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整合

      本文链接:https://www.haomeiwen.com/subject/gfdywctx.html