今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作。
<强>步骤一:强>在pom.xml文件中添加MYSQl和JPA的相关的Jar包依赖,具体添加位置在依赖关系中,具体添加的内容如下所示。
& lt; !——数据库相关配置——比; & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-web & lt;/dependency> & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-data-jpa & lt;/dependency> & lt; dependency> & lt; groupId> mysql & lt; artifactId> mysql-connector-java & lt;/dependency> & lt; dependency> & lt; groupId> org.apache.poi & lt; artifactId> poi & lt; version> 3.11 & lt;/version> & lt;/dependency> >之前<强>步骤二:强>在application.properties配置文件中加入数据库的相关配置,配置信息如下所示。
spring.datasource。url=jdbc: mysql://localhost: 3306/webtest spring.datasource。用户名=根 spring.datasource。密码=220316 spring.datasource。driverClassName=com.mysql.jdbc.Driver #指定数据库管理系统 spring.jpa.database=MYSQL #显示或不为每个sql查询日志 spring.jpa.show-sql=true # Hibernate ddl汽车(创建、create-drop、更新) spring.jpa.hibernate.ddl-auto=更新 #命名策略 spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy #将它们添加到实体管理器之前删除) spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect >之前这里给大家解释一下:webtest代表数据库名称,根是用户名,220316年是密码
<强>步骤三:强>编写数据库操作的实体类,实体类具体信息如下所示:
包example.entity; 进口javax.persistence。*; 进口javax.validation.constraints.NotNull; 进口java.math.BigDecimal; 进口java.util.Date; @ entity @ table (name="用户") 公开课用户{ @ id @GeneratedValue(策略=GenerationType.AUTO) 私人int id; @ column (name=懊帧?可空=true,长度=30) 私人字符串名称; @ column (name="高度" nullable=true,长度=10) 私人int高度; @ column (name=靶浴?可以为空=true,长度=2) 私人char性; @Temporal (TemporalType.DATE) 私人生日日期; @Temporal (TemporalType.TIMESTAMP) 私人sendtime日期;//日期类型、格式:yyyy-MM-dd HH: mm: ss @ column (name="价格",可空=true,长度=10) 私人BigDecimal价格; @ column (name=" floatprice nullable=true,长度=10) 私人floatprice浮动; @ column (name=" doubleprice nullable=true,长度=10) 私人双doubleprice; 上市日期getSendtime () { 返回sendtime; } 公共空间setSendtime(日期sendtime) { 这一点。sendtime=sendtime; } 公共BigDecimal getPrice () { 回报价格; } 公共空间setPrice (BigDecimal价格){ 这一点。价格=价格; } 公共浮动getFloatprice () { 返回floatprice; } 公共空间setFloatprice(浮动floatprice) { 这一点。floatprice=floatprice; } 公共双getDoubleprice () { 返回doubleprice; } 公共空间setDoubleprice(双doubleprice) { 这一点。doubleprice=doubleprice; } 公共用户(){} 公共字符getSex () { 返回性; } 公共空间setSex (char性){ 这一点。性别=性; } 上市日期getBirthday () { 返回的生日; } 公共空间setBirthday(日期的生日){ 这一点。生日=生日; } 公共用户(int id) { 这一点。id=id; } 公共int getId () { 返回id; } 公共空间setId (int id) { 这一点。id=id; } 公共字符串getName () { 返回名称; } 公共空间setName(字符串名称){ this.name=名称; } 公共int获得(){ 回报高; } 公共空间setHeight (int高度){ 这一点。身高=身高; } }SpringBoot连接MYSQL数据库并使用JPA进行操作