mybaitis连接数据库

开发中经常说到数据入库,我们在实现时需要知道使用何种技术,连接哪个数据库,连接数据库的账号和密码等等。

今天要跟大家分享的是spring web项目中使用mybatis连接到postgresql中。以本机数据库为例(即数据库由本机启动)。

1、安装postgresql,并安装postGIS扩展,建议安装pgadmin方便使用。安装过程不再赘述,网上教程多且详细。

2、执行下列代码可以查看postgresql、postGIS版本信息,执行失败则安装不成果

select version();  // 可以查看postgresql的版本信息。
SELECT PostGIS_full_version(); // 查看postGIS版本信息



3、在项目的pom.xml文件中配置依赖


    org.mybatis
    mybatis
    3.5.5


    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.2.2


    org.postgresql
    postgresql

4、mapper类、启动类中添加注解

@Mapper
public interface ShpMapper {
    int insertFeatureList(@Param("featureList") List featureModelList);
}
@SpringBootApplication
@MapperScan("com.example.geoservice.mapper")
public class GeoServiceApplication {

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

}

5、写配置文件application.properties(前) 或者 application.yml(后)

#配置mapper的扫描路径
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# 地址:端口号/数据库名称
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres?useSSL=false
spring.datasource.username=postgres
spring.datasource.password=123456
spring.datasource.driver-class-name=org.postgresql.Driver
spring:
  datasource:
    driver-class-name: org. postgresql. Driver
    url: jdbc:postgresql://localhost:5432/postgres?useSSL=false
    username: postgres
    password: 123456

mybatis:
  mapper -locations: classpath:mapper/* . xml
  

6、运行时常见错误及解决办法(1)

 Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-08-28 17:06:47.402 ERROR 13520 --- [      main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
    APPLICATION FAILED TO START
***************************

    Description:

    Field shpMapper in com.example.geoservice.service.Impl.ShpServiceImpl required a bean of type 'com.example.geoservice.mapper.ShpMapper' that could not be found.

    The injection point has the following annotations:
            - @org.springframework.beans.factory.annotation.Autowired(required=true)

    Action:

    Consider defining a bean of type 'com.example.geoservice.mapper.ShpMapper' in your configuration.

解决办法:在pom文件中添加依赖,在启动类中添加扫描路径



6、运行时常见错误及解决办法(2)- 忘记数据库用户名和密码

①查看用户:在数据库上右键 -> 属性,在“常规”中可以看到所有者


②修改密码。忘记密码查看密码比较麻烦,这里建议直接修改密码。

ALTER USER postgres WITH PASSWORD '123456';


7、mybatis的mapper和xml跳转,推荐使用插件mybaitisx

点击file -> setting -> Plugins -> Marketplace ,搜索mybatisx安装

效果,点击这个黑色的鸟,可以实现相互跳转



分享完毕。

1、介绍mybaitis的基础配置,

2、给出了mapper类的基础样例,

3、给出无启动依赖时报错解决方法,

4、通过pgadmin查看数据库账户,给出修改密码的方法

5、跳转插件mybaitisX推荐

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章