您的位置:首页 > 编程语言 > Java开发

3、spring-boot访问数据库

2017-11-26 20:59 351 查看
1、在之前的基础上添加两个包

<dependency><!-- 数据库驱动包 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency><!-- 据说可以使对象持久化,待我了解后再来更新 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>


**2、创建source folder源文件夹,在其中创建application.properties文件,

application.properties中代码如下所示**

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root#这里写密码
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

########################################################
### Java Persistence Api
########################################################
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


**3、新建一个实体类,并在期中加入注解@Entity和@Id和@GeneratedValue

代码如下所示:**

@Entity
public class Demo {
@Id
@GeneratedValue
private int id;
private String name;

public long getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}


PS:在这里你要注意,在我上面第二步给出的代码

spring.datasource.url = jdbc:mysql://localhost:3306/test


中,连接的数据库test要提前建好,因为hibernate只会建表,不会建库。

4、运行结果:test数据库中生成了一个Demo表

(记得刷新一下数据库才能看见噢,我就吃了这个亏)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: