首页 > 数据库 >SpringBoot入门系列: JPA mysql(五)

SpringBoot入门系列: JPA mysql(五)

时间:2022-12-14 15:35:02浏览次数:67  
标签:SpringBoot JPA org mysql String address import public name


一,准备工作,建立spring-boot-sample-mysql工程

1、http://start.spring.io/

     A、Artifact中输入spring-boot-sample-mysql

     B、勾选Web下的web

     C、勾选SQL下的JPA MYSQL

2、Eclips中导入工程spring-boot-sample-mysql

     A、解压快捷工程spring-boot-sample-mysql到某文件夹

     B、eclips中file->import->Import Existing Maven Projects–>Select Maven projects–>finish导入工程

3、工程导入之后,文件结构如下图


4、在包com.example下建立web文件夹


5、便于测试,引入spring-boot-sample-helloworld的HelloController及配置文件logback.xml

HelloController代码为

package com.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

protected static Logger logger=LoggerFactory.getLogger(HelloController.class);

@RequestMapping("/")
public String helloworld(){
logger.debug("访问hello");
return "Hello world!";
}

@RequestMapping("/hello/{name}")
public String helloName(@PathVariable String name){
logger.debug("访问helloName,Name={}",name);
return "Hello "+name;
}
}

logback.xml配置为


<configuration>  
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<charset>GBK</charset>
</encoder>
</appender>
<appender name="baselog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>log/base.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/base.log.%d.i%</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 64 MB -->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<logger name="com.example" level="DEBUG">
<appender-ref ref="baselog" />
</logger>
</configuration>

注:logback.xml文件位于src/main/resources下


6、启动工程,通过浏览器查看正确性

​http://localhost:8080/​

​ http://localhost:8080/hello/上帝 ​

二,使用JPA,构建业务对象及访问库

1、在包com.example下建立domain文件夹


2、在domain中建立类Person

package com.example.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {

@Id
@GeneratedValue
private Long id;

private String name;

private Integer age;

private String address;

public Person() {
super();
}

public Person(Long id, String name, Integer age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

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

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

注意:构造函数


3、在包com.example下建立repository文件夹

4、在repository中建立接口PersonRepository

package com.example.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.domain.Person;

@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {

List<Person> findByName(String name);

List<Person> findByAddress(String address);

List<Person> findByNameAndAddress(String name,String address);

@Query("select p from Person p where p.name=:name and p.address=:address")
List<Person> withNameAndAddressQuery(@Param("name")String Name,@Param("address")String address);
}

5、在web中建立DataController


package com.example.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.domain.Person;
import com.example.repository.PersonRepository;

@RestController
public class DataController {

protected static Logger logger=LoggerFactory.getLogger(DataController.class);

@Autowired
PersonRepository personRepository;

@RequestMapping("/save")
public Person save(String name,String address,Integer age){
logger.debug("save 开始");
Person p=personRepository.save(new Person(null,name,age,address));
logger.debug("save 结束");
return p;
}

@RequestMapping("/q1")
public List<Person> q1(String address){
logger.debug("q1 开始");
logger.debug("q1 接收参数address={}",address);
List<Person> people=personRepository.findByAddress(address);
return people;
}

@RequestMapping("/q2")
public List<Person> q2(String name,String address){
logger.debug("q2 开始");
logger.debug("q2接收参数name={},address={}",name,address);
return personRepository.findByNameAndAddress(name, address);
}

@RequestMapping("/q3")
public List<Person> q3(String name,String address){
logger.debug("q3 开始");
logger.debug("q3接收参数name={},address={}",name,address);
return personRepository.withNameAndAddressQuery(name, address);
}

@RequestMapping("/sort")
public List<Person> sort(){
logger.debug("sort 开始");
List<Person> people=personRepository.findAll(new Sort(Direction.ASC,"age"));
return people;
}

@RequestMapping("/page")
public Page<Person> page(){
logger.debug("page 开始");
Page<Person> people=personRepository.findAll(new PageRequest(1,2));
return people;
}
}

6、配置数据库连接,在application.properties(src/main/resources下)


spring.datasource.url=jdbc:mysql://192.168.56.201:3306/bootsample?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true

7、运行测试

A、先保存数据

​http://localhost:8080/save?name=aa&&address=北京&&age=1​​​ http://localhost:8080/save?name=ab&&address=北京&&age=2
http://localhost:8080/save?name=cq1&&address=重庆&&age=50
http://localhost:8080/save?name=cq2&&address=重庆&&age=51

B、查询q1

​http://localhost:8080/q1?address=北京​

C、查询q2

​http://localhost:8080/q2?address=北京&&name=aa​

D、查询q3

​http://localhost:8080/q3?address=北京&&name=aa​

E、排序

​http://localhost:8080/sort​

F、分页

​http://localhost:8080/page​


运用hibernate访问mysql,基本也是老技术,只是用JPA简化了dao层代码,对于业务对象基本没有变化。



一,准备工作,建立spring-boot-sample-mysql工程

1、http://start.spring.io/

     A、Artifact中输入spring-boot-sample-mysql

     B、勾选Web下的web

     C、勾选SQL下的JPA MYSQL

2、Eclips中导入工程spring-boot-sample-mysql

     A、解压快捷工程spring-boot-sample-mysql到某文件夹

     B、eclips中file->import->Import Existing Maven Projects–>Select Maven projects–>finish导入工程

3、工程导入之后,文件结构如下图


4、在包com.example下建立web文件夹


5、便于测试,引入spring-boot-sample-helloworld的HelloController及配置文件logback.xml

HelloController代码为

package com.example.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

protected static Logger logger=LoggerFactory.getLogger(HelloController.class);

@RequestMapping("/")
public String helloworld(){
logger.debug("访问hello");
return "Hello world!";
}

@RequestMapping("/hello/{name}")
public String helloName(@PathVariable String name){
logger.debug("访问helloName,Name={}",name);
return "Hello "+name;
}
}

logback.xml配置为


<configuration>  
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<charset>GBK</charset>
</encoder>
</appender>
<appender name="baselog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>log/base.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/base.log.%d.i%</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 64 MB -->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<logger name="com.example" level="DEBUG">
<appender-ref ref="baselog" />
</logger>
</configuration>

注:logback.xml文件位于src/main/resources下


6、启动工程,通过浏览器查看正确性

​http://localhost:8080/​

​ http://localhost:8080/hello/上帝 ​

二,使用JPA,构建业务对象及访问库

1、在包com.example下建立domain文件夹


2、在domain中建立类Person

package com.example.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {

@Id
@GeneratedValue
private Long id;

private String name;

private Integer age;

private String address;

public Person() {
super();
}

public Person(Long id, String name, Integer age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

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

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

注意:构造函数


3、在包com.example下建立repository文件夹

4、在repository中建立接口PersonRepository

package com.example.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.domain.Person;

@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {

List<Person> findByName(String name);

List<Person> findByAddress(String address);

List<Person> findByNameAndAddress(String name,String address);

@Query("select p from Person p where p.name=:name and p.address=:address")
List<Person> withNameAndAddressQuery(@Param("name")String Name,@Param("address")String address);
}

5、在web中建立DataController


package com.example.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.domain.Person;
import com.example.repository.PersonRepository;

@RestController
public class DataController {

protected static Logger logger=LoggerFactory.getLogger(DataController.class);

@Autowired
PersonRepository personRepository;

@RequestMapping("/save")
public Person save(String name,String address,Integer age){
logger.debug("save 开始");
Person p=personRepository.save(new Person(null,name,age,address));
logger.debug("save 结束");
return p;
}

@RequestMapping("/q1")
public List<Person> q1(String address){
logger.debug("q1 开始");
logger.debug("q1 接收参数address={}",address);
List<Person> people=personRepository.findByAddress(address);
return people;
}

@RequestMapping("/q2")
public List<Person> q2(String name,String address){
logger.debug("q2 开始");
logger.debug("q2接收参数name={},address={}",name,address);
return personRepository.findByNameAndAddress(name, address);
}

@RequestMapping("/q3")
public List<Person> q3(String name,String address){
logger.debug("q3 开始");
logger.debug("q3接收参数name={},address={}",name,address);
return personRepository.withNameAndAddressQuery(name, address);
}

@RequestMapping("/sort")
public List<Person> sort(){
logger.debug("sort 开始");
List<Person> people=personRepository.findAll(new Sort(Direction.ASC,"age"));
return people;
}

@RequestMapping("/page")
public Page<Person> page(){
logger.debug("page 开始");
Page<Person> people=personRepository.findAll(new PageRequest(1,2));
return people;
}
}

6、配置数据库连接,在application.properties(src/main/resources下)


spring.datasource.url=jdbc:mysql://192.168.56.201:3306/bootsample?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true

7、运行测试

A、先保存数据

​http://localhost:8080/save?name=aa&&address=北京&&age=1​​​ http://localhost:8080/save?name=ab&&address=北京&&age=2
http://localhost:8080/save?name=cq1&&address=重庆&&age=50
http://localhost:8080/save?name=cq2&&address=重庆&&age=51

B、查询q1

​http://localhost:8080/q1?address=北京​

C、查询q2

​http://localhost:8080/q2?address=北京&&name=aa​

D、查询q3

​http://localhost:8080/q3?address=北京&&name=aa​

E、排序

​http://localhost:8080/sort​

F、分页

​http://localhost:8080/page​


运用hibernate访问mysql,基本也是老技术,只是用JPA简化了dao层代码,对于业务对象基本没有变化。


标签:SpringBoot,JPA,org,mysql,String,address,import,public,name
From: https://blog.51cto.com/u_15912341/5937204

相关文章

  • SpringBoot入门:Hello World(一)
       跟随SpringBoot的文档(http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-documentation)学习,前后几章关联才调通代码,煞是痛苦,在......
  • 关于在springboot中的controller引入不了service报错解决办法
    关于在springboot中的controller引入不了service报错解决办法报错如下:不仅是controller一层出现问题,每一层都是相同的问题解决步骤:1.当出现了这个错误不要慌,首先清......
  • 项目迁移中 遇到的MySQL问题
    两个问题都是数据库迁移导致的  1.Expression#16ofSELECTlistisnotinGROUPBYclauseandcontainsnonaggregatedcolumn'sanghe.a.contract_no'whichisno......
  • docker-compose + mysql8.x 主从数据库配置
    0.准备(略过docker的安装与镜像拉取)docker/docker-compose安装拉取mysql8.x 1.master和slave的mysql配置master:[mysqld]server-id=11118log-bin=mysql-bi......
  • MySQL 面试题总结
    MySQL的面试知识点总结Q1:MySQL的逻辑架构了解吗?第一层是服务器层,主要提供连接处理、授权认证、安全等功能。第二层实现了MySQL核心服务功能,包括查询解析、分析、优......
  • Nacos-配置中心,特性,启动,集成mysql,快速入门
    Nacos-配置管理目录Nacos-配置管理1.什么是配置中心1.1什么是配置1.2什么是配置中心2Nacos****简介2.1主流配置中心对比2.2Nacos****简介2.3Nacos****特性3Na......
  • SpringBoot(五):JSR303校验
    一、什么是JSR303校验JSR,是JavaSpecificationRequests的缩写,意思是Java规范提案,是指向JCP(JavaCommunityProcess)提出新增一个标准化技术规范的正式请求。JCP(JavaCo......
  • 3:表的基本操作-MySQL
    (目录)3.1提出问题,引入“表“的概念与思维模式table表的概念:数据库类似于厂库,而表呢就是对数据进行抽象分类的货架注意:在创建数据库的时候一定要记得设置字符编码......
  • springboot依靠注解的定时任务与hutool的定时任务
    在学习hutool文档时发现它也有一个定时任务,怎么实现的呢?resources目录下创建一个config目录,config目录下创建cron.setting文件[com.fzg.common.demo.uuid]UUIDdemo......
  • 记一次节点被mysql锁定的异常处理
    参考:https://blog.csdn.net/weixin_34293141/article/details/93057113同事反馈公司的一个java客户端工具运行异常,后台log如下:2022-12-0810:52:28WARNBasicResourc......