主要描述如何优雅的整合postgresql。本文略去如何安装pgsql的过程,详情可参考其他文章。
与mysql一样也是开源的关系型数据库,同时还支持NoSql的文档型存储。在某些方面标榜比mysql表现更加出众,现在就让我们来了解下如何使用postgresql。
org.postgresql postgresql org.springframework.boot spring-boot-starter-jdbc 3.0.4 org.projectlombok lombok 1.18.26
spring:
datasource:
driver-class-name: org.postgresql.Driver
username: postgres
password: root
url: jdbc:postgresql://127.0.0.1:5432/postgres
此处我们预先新建一个test表,查询该表的记录数,当前表中有一条记录。
@Slf4j
@SpringBootTest
class MypgApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() {
Long count = jdbcTemplate.queryForObject("select count(*) from test", Long.class);
log.info("记录总数:{}",count);
}
}
记录总数:1
以上我们直接使用jdbc进行数据操作,接下来我们使用mybatis进行改造。
org.mybatis.spring.boot mybatis-spring-boot-starter 2.3.0
mybatis:
mapper-locations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@Data
public class Test {
private Long id;
}
public interface TestMapper {
Long queryForMybatis(Test testDO);
}
@Service
public class TestService {
@Resource
private TestMapper testMapper;
public Long queryForMybatis(Test testDO){
return testMapper.queryForMybatis(testDO);
}
}
@MapperScan("com.vainycos.dao")
@SpringBootApplication
public class MypgApplication {
public static void main(String[] args) {
SpringApplication.run(MypgApplication.class, args);
}
}
com.baomidou mybatis-plus-boot-starter 3.4.3
public interface TestMapper extends BaseMapper{ Long queryForMybatis(Test testDO); }
public Long queryForMybatisPlus(Test testDO){
Integer resultCount = testMapper.selectCount(new LambdaQueryWrapper()
.eq(testDO.getId() != null, Test::getId, testDO.getId())
);
return resultCount.longValue();
}
@GetMapping("/queryForMybatisPlus")
public Long queryForMybatisPlus(Test testDO){
return testService.queryForMybatisPlus(testDO);
}
参考资料: