主要描述如何优雅的整合postgresql。本文略去如何安装pgsql的过程,详情可参考其他文章。
与mysql一样也是开源的关系型数据库,同时还支持NoSql的文档型存储。在某些方面标榜比mysql表现更加出众,现在就让我们来了解下如何使用postgresql。
<dependency>
<groupId>org.postgresqlgroupId>
<artifactId>postgresqlartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
<version>3.0.4version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.26version>
dependency>
spring:
datasource:
driver-class-name: org.postgresql.Driver
username: postgres
password: root
url: jdbc:postgresql://127.0.0.1:5432/postgres
@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进行改造。
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.3.0version>
dependency>
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);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vainycos.dao.TestMapper">
<select id="queryForMybatis" parameterType="com.vainycos.domain.Test" resultType="java.lang.Long">
select count(*) from test
<where>
<if test="id != null and id != ''">
and id = #{id}
if>
where>
select>
mapper>
@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);
}
}
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.3version>
dependency>
public interface TestMapper extends BaseMapper<Test> {
Long queryForMybatis(Test testDO);
}
public Long queryForMybatisPlus(Test testDO){
Integer resultCount = testMapper.selectCount(new LambdaQueryWrapper<Test>()
.eq(testDO.getId() != null, Test::getId, testDO.getId())
);
return resultCount.longValue();
}
@GetMapping("/queryForMybatisPlus")
public Long queryForMybatisPlus(Test testDO){
return testService.queryForMybatisPlus(testDO);
}
参考资料: