mysql和springboot对照_SpringBoot(六) SpirngBoot与Mysql关系型数据库

pom.xml文件的配置

org.springframework.boot

spring-boot-starter-jdbc

mysql

mysql-connector-java

runtime

写配置文件

spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8

spring.datasource.username = root

spring.datasource.password = root

spring.datasource.driver-class-name = com.mysql.jdbc.Driver

spring:

datasource:

username: root

password: Welcome_1

url: jdbc:mysql://192.168.179.131:3306/jdbc

driver-class-name: com.mysql.jdbc.Driver

type: com.alibaba.druid.pool.DruidDataSource

# schema:

# - classpath:department.sql

server:

port: 9000

自定义数据源DRUID

spring-boot-starter-jdbc 默认使用tomcat-jdbc数据源,如果你想使用其他的数据源,比如这里使用了阿里巴巴的数据池管理,你应该额外添加以下依赖:

com.alibaba

druid

1.0.19

编写java测试链接代码

@SpringBootApplicationpublic classApplication {public static voidmain(String[] args) {

SpringApplication.run(Application.class, args);

}//destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.

@Bean(destroyMethod = "close")publicDataSource dataSource() {

DruidDataSource dataSource= newDruidDataSource();

dataSource.setUrl(env.getProperty("spring.datasource.url"));

dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名

dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码

dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));

dataSource.setInitialSize(2);//初始化时建立物理连接的个数

dataSource.setMaxActive(20);//最大连接池数量

dataSource.setMinIdle(0);//最小连接池数量

dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。

dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql

dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效

dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。

dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache

returndataSource;

}

}

spring:

datasource:

username: root

password: Welcome_1

url: jdbc:mysql://192.168.179.131:3306/jdbc

driver-class-name: com.mysql.jdbc.Driver

type: com.alibaba.druid.pool.DruidDataSource

# 初始化大小,最小,最大

initialSize: 5

minIdle: 5

maxActive: 20

# 配置获取连接等待超时的时间

maxWait: 60000

# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

timeBetweenEvictionRunsMillis: 60000

# 配置一个连接在池中最小生存的时间,单位是毫秒

minEvictableIdleTimeMillis: 300000

validationQuery: SELECT 1 FROM DUAL

testWhileIdle: true

testOnBorrow: false

testOnReturn: false

poolPreparedStatements: true

# 配置监控统计拦截的filters,去掉监控界面sql无法统计,‘wall’用于防火墙

filters: stat,wall,log4j

maxPoolPreparedStatementPerConnectionSize: 20

userGlobalDataSourceStat: true

# 通过connectProperties属性来打开mergeSql功能;慢SQL记录

connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

# schema:

# - classpath:department.sql

server:

port: 9000

编写测试代码

@Repositorypublic class LearnDaoImpl implementsLearnDao{

@AutowiredprivateJdbcTemplate jdbcTemplate;

@Overridepublic intadd(LearnResouce learnResouce) {return jdbcTemplate.update("insert into learn_resource(author, title,url) values(?, ?, ?)",learnResouce.getAuthor(),learnResouce.getTitle(),learnResouce.getUrl());

}

@Overridepublic Page queryLearnResouceList(Mapparams) {

StringBuffer sql=newStringBuffer();

sql.append("select * from learn_resource where 1=1");if(!StringUtil.isNull((String)params.get("author"))){

sql.append(" and author like '%").append((String)params.get("author")).append("%'");

}if(!StringUtil.isNull((String)params.get("title"))){

sql.append(" and title like '%").append((String)params.get("title")).append("%'");

}

Page page= new Page(sql.toString(), Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()), jdbcTemplate);returnpage;

}

}

@Configuration

public class DruidConfig {

@ConfigurationProperties(prefix = "spring.datasource")

@Bean

public DataSource druid(){

return new DruidDataSource();

}

//配置Druid的监控

//1、配置一个管理后台

@Bean

public ServletRegistrationBean statViewServlet(){

ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

Map initParams =new HashMap<>();

initParams.put("loginUsername", "admin");

initParams.put("loginPassword", "123456");

bean.setInitParameters(initParams);

return bean;

}

//2、配置监控的filter

@Bean

public FilterRegistrationBean webstatFilter(){

FilterRegistrationBean bean = new FilterRegistrationBean();

bean.setFilter(new WebStatFilter());

Map initParams =new HashMap<>();

initParams.put("exclusions", "*.js,*.css,/druid/*");

bean.setInitParameters(initParams);

bean.setUrlPatterns(Arrays.asList("/*"));

return bean;

}

}

访问:localhost:8080/druid/login.html

以上是使用JDBCTemptlate模板,可以参考API文档    JdbcTemplate

SpringBoot整合Mybatis

1.使用注解的方式

导入依赖

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.3.2

com.alibaba

druid

1.1.9

mysql

mysql-connector-java

runtime

org.springframework.boot

spring-boot-starter-jdbc

导入配置文件中关于Druid的配置

创建数据表

创建数据库对应的JavaBean,以及getter和setter方法

在配置文件中修改驼峰命名开启 ,不写配置文件就写配置类

mybatis:

configuration:

map-underscore-to-camel-case: true

数据库中以下划线分割,而javabean中以驼峰命名。解决办法

public class MyBatisConfig {

@Bean

public ConfigurationCustomizer configurationCustomizer(){

return new ConfigurationCustomizer() {

@Override

public void customize(Configuration configuration) {

configuration.setMapUnderscoreToCamelCase(true);

}

};

}

}

使用注解方式导入mapper

@MapperScan(value = "com.test.testMapper")

编写测试类(@component注解不添加也没事,只是不加service那边引入mapper的时候会有错误提示,也就是红线,但不影响程序的运行)

@Component

@Mapper

public interface DepartmentMapper {

@Insert("insert into department(dept_name) value(#{deptName})")

public int insertDept(Department department);

@Delete("delete from department where id=#{id}")

public int deleteDeptById(Integer id);

@Update("update department set dept_Name=#{deptName} where id=#{id}")

public int updateDept(Department department);

@Select("select * from department where id=#{id}")

public Department getDeptById(Integer id);

}

配置文件的方式整合Mybatis(xml方式)

新建mybatis的配置文件。

/p>

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

新建mapper接口及其方法。

public interface EmployeeMapper {

public Employee getEmpById(Integer id);

public void insetEmp(Employee employee);

}

新建Employee的mapper.xml的映射文件

/p>

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from employee where id=#{id}

INSERT INTO employee(last_name,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})

修改application.yml配置文件

mybatis:

config-location: classpath:mybatis/mybatis-config.xml

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

编写controller类进行测试。更多的mybatis使用查询官方文档。mybatis官方中文参考文档

PageHelper分页插件

导入pom.xml

com.github.pagehelper

pagehelper

x.x.x

例子

//2. use static method startPage

PageHelper.startPage(1, 10);

List list = countryMapper.selectIf(1);//3. use static method offsetPage

PageHelper.offsetPage(1, 10);

List list = countryMapper.selectIf(1);//4. method parameters

public interfaceCountryMapper {

ListselectByPageNumSize(

@Param("user") User user,

@Param("pageNum") intpageNum,

@Param("pageSize") intpageSize);

}//config supportMethodsArguments=true

List list = countryMapper.selectByPageNumSize(user, 1, 10);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以通过使用多个数据源来同时连接MySQL和Neo4j数据库。 首先,我们需要在Spring Boot的配置文件中设置两个数据源的相关属性。对于MySQL数据库,我们可以使用以下配置: spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver 对于Neo4j数据库,我们可以使用以下配置: spring.data.neo4j.uri=bolt://localhost:7687 spring.data.neo4j.username=neo4j spring.data.neo4j.password=password 同时,我们需要在Spring Boot应用程序中定义两个数据源的bean。可以使用以下方式: @Configuration public class DataSourceConfig { @Bean(name = "mysqlDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource mysqlDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "neo4jDataSource") @ConfigurationProperties(prefix = "spring.data.neo4j") public DataSource neo4jDataSource() { return DataSourceBuilder.create().build(); } } 接下来,在需要使用数据库的地方,可以使用@Qualifier注解来指定具体的数据源。 @Autowired @Qualifier("mysqlDataSource") private DataSource mysqlDataSource; @Autowired @Qualifier("neo4jDataSource") private DataSource neo4jDataSource; 这样,我们就可以同时连接MySQL和Neo4j数据库并使用它们来进行相应的操作了。 ### 回答2: Spring Boot可以同时连接MySQL和Neo4j数据库。首先,需要在pom.xml文件中添加相应的依赖。 对于连接MySQL数据库,可以使用Spring Boot提供的Spring Data JPA。在pom.xml中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 然后,在application.properties文件中配置MySQL相关属性,如数据库连接URL、用户名和密码等。 接下来,要连接Neo4j数据库,可以使用Spring Boot提供的Spring Data Neo4j。在pom.xml中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-neo4j</artifactId> </dependency> <dependency> <groupId>org.neo4j</groupId> <artifactId>neo4j-ogm-embedded-driver</artifactId> </dependency> ``` 然后,在application.properties文件中配置Neo4j相关属性,如数据库路径等。 最后,可以分别创建对应的Repository接口,使用注解指定对应的数据库和表。 通过以上步骤,就可以同时连接MySQL和Neo4j数据库。在编写业务逻辑时,可以通过注入对应的Repository接口来使用数据库操作方法,以实现对两种数据库的数据读写。 ### 回答3: Spring Boot可以同时连接MySQL和Neo4j数据库。连接MySQL数据库需要添加MySQL驱动依赖,例如: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 然后在应用的配置文件中配置MySQL数据库的连接信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 连接Neo4j数据库需要添加Neo4j驱动依赖,例如: ```xml <dependency> <groupId>org.neo4j.driver</groupId> <artifactId>neo4j-java-driver</artifactId> </dependency> ``` 然后在应用的配置文件中配置Neo4j数据库的连接信息,例如: ```properties spring.data.neo4j.uri=bolt://localhost spring.data.neo4j.username=neo4j spring.data.neo4j.password=123456 ``` 接下来,可以通过Spring Boot的数据访问层(如JPA或Spring Data Neo4j)来访问MySQL和Neo4j数据库。 对于MySQL数据库,可以使用JPA来进行数据访问,例如创建一个实体类并加上`@Entity`和`@Table`注解,定义实体的属性和数据库表的映射关系。然后可以创建一个`Repository`接口继承`CrudRepository`接口,通过编写简单的方法签名可以实现对数据库的增删改查操作。 对于Neo4j数据库,可以使用Spring Data Neo4j来进行数据访问,例如创建一个节点实体类并加上`@Node`注解,定义节点的属性。然后可以创建一个`@Repository`接口,使用Cypher语句进行数据访问操作。可以通过`@Query`注解编写自定义的Cypher语句,或者使用Spring Data Neo4j提供的自动解析方法名称的功能。 这样,就可以在Spring Boot应用中同时连接MySQL和Neo4j数据库,并进行相应的数据访问操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值