3、spring-boot访问数据库

来源:互联网 发布:淘宝助理如何图片搬家 编辑:程序博客网 时间:2024/05/21 19:49

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/testspring.datasource.username = rootspring.datasource.password = root#这里写密码spring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.max-active=20spring.datasource.max-idle=8spring.datasource.min-idle=8spring.datasource.initial-size=10########################################################### Java Persistence Api######################################################### Specify the DBMSspring.jpa.database = MYSQL# Show or not log for each sql queryspring.jpa.show-sql = true# Hibernate ddl auto (create, create-drop, update)spring.jpa.hibernate.ddl-auto = update# Naming strategyspring.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
代码如下所示:**

@Entitypublic 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表
(记得刷新一下数据库才能看见噢,我就吃了这个亏)

原创粉丝点击