SpringBoot整合各种持久层技术

上一篇 << 下一篇 >>>SpringBoot整合Mybatis分页插件


通用配置

a.添加数据库驱动依赖



    mysql
    mysql-connector-java

b.在maven工程的main/java/resources目录下名为“application.yml”的配置文件中配置数据库信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

1.整合jdbctemplate

注意: spring-boot-starter-parent要在1.5以上,添加相关的依赖及代码演示



    org.springframework.boot
    spring-boot-starter-jdbc


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void createUser(String name, Integer age) {
        jdbcTemplate.update("insert into users values(null,?,?);", name, age);
    }
}

2.整合mybatis

添加相关依赖及代码演示


    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.1.1


public interface UserMapper {
    @Select("SELECT * FROM USERS WHERE NAME = #{name}")
    User findByName(@Param("name") String name);
    @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);
}
##启动类上要加@MapperScan,或者在每个Mapper上加@Mapper注解才会生效
@MapperScan("com.jarye.mapper")
@SpringBootApplication
public class MybatisApp {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApp.class, args);
    }
}

3.整合JPA

添加相关依赖及代码演示


    org.springframework.boot
    spring-boot-starter-data-jpa


@Entity(name = "users")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "age")
    private Integer age;
}

public interface UserDao extends JpaRepository {
}

@RestController
public class IndexController {
    @Autowired
    private UserDao userDao;

    @RequestMapping("/jpaFindUser")
    public Object jpaIndex(User user) {
        Optional userOptional = userDao.findById(user.getId());
        User reusltUser = userOptional.get();
        return reusltUser == null ? "没有查询到数据" : reusltUser;
    }
}

推荐阅读:
<< << <<<如何自定义SpringBoot starter
<< << << << << << << << << <<

你可能感兴趣的:(SpringBoot整合各种持久层技术)