Springboot+mysql增删改查
用IDEA直接构建springboot项目,点击spring initializer 即可进行下一步,不会的自己百度。直接上代码
目录结构如下:
1.pom.xml :这个里面一般没啥问题,只要把jar包加载完毕就没问题
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>comg.song</groupId>
<artifactId>springboot-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<!--web 支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--jsp页面使用jstl标签-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--用于编译jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!--springboot用JPA连接mysql数据库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.Application.properties
#连接mysql数据库
spring.datasource.url=jdbc:mysql://localhost:3306/thirdteam?useSSL=false&characterEncoding=UTF-8&?useUnicode=true
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.tomcat.uri-encoding=UTF-8
#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#视图配置
spring.mvc.view.prefix= /WEB-INF/view/
spring.mvc.view.suffix= .jsp
提示:thirdteam是我的数据库名字,useSSL=false写这句话有一定原因的。一般来说,如今发布的高版本Mysql都需要设置SSL(true/false),如果不设置,会出现如下报错。
Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
3.Controller层
package com.song.controller;
import com.song.Dao.PersonRepository;
import com.song.pojo.Person;
import com.song.service.PersonService;
import com.sun.org.apache.bcel.internal.generic.MONITORENTER;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Song on 2017/2/15.
* User控制层
*/
@Controller
public class UserController {
@Autowired
PersonService personService;
/**
* 查询所有的数据内容
* @return
*/
@RequestMapping(value = "/name",method = RequestMethod.GET)
public String list(String name,Model model){
List<Person> person=personService.findByName(name);
model.addAttribute("person",person);
return "index";
}
/**
* 通过地址查询
* @param address
* @return
*/
@RequestMapping(value = "/address",method = RequestMethod.GET)
public String findByAddress(String address,Model model){
List<Person> person= personService.findByAddress(address);
model.addAttribute("person",person);
return "index";
}
/**
* 查询的另外一种方式
* @param name
* @param address
* @return
*/
@RequestMapping(value = "/Na_Add",method = RequestMethod.GET)
public String withNameAndAddressQuery(String name,String address,Model model){
List<Person> person=personService.withNameAndAddressQuery(name,address);
model.addAttribute("person",person);
return "index";
}
/**
* 删除
* @param name
* @param model
* @return
*/
@RequestMapping(value = "/Del_name",method = RequestMethod.GET)
public String deleteByName(String name,Model model){
int a=personService.deleteByName(name);
model.addAttribute("person",a);
return "index";
}
/**
* 增加一行数据
* @param name
* @param age
* @param address
* @param model
* @return
*/
@RequestMapping(value = "/Add",method = RequestMethod.GET)
public String Add(String name,int age,String address,Model model){
int a=personService.Add(name,age,address);
return "index";
}
/**
* 修改一行数据
* @param id
* @param name
* @return
*/
@RequestMapping(value = "/Modify",method = RequestMethod.GET)
public int modify(int id,String name){
int a=personService.modify(id,name);
return a;
}
}
对于在Conroller层添加@controller 和@RestConroller这件事,有个解释
1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
意思就是:
@RestController注解会使返回的内容不进入到视图解析器,也就是返回的是单纯的文本信息(先这么理解)。
@Controller注解表示返回的内容会进入到视图解析器,比如你在application.properties中配置了这个:
#视图配置 spring.mvc.view.prefix= /WEB-INF/view/ spring.mvc.view.suffix= .jsp
你返回的是index字符串(return "index";),那么最后视图解析器解析后,会到webapp/WEB-INF/view/index.jsp页面。
多插一句:webapp是怎么手动生成的呢?如果直接新建文件夹的话,运行一下就会报错。
会玩IDEA的一看就懂了,直接设置好右面web.xml和webapp位置,下面三个对号全打上。没有webapp这一项,你就点击spring上面加号,选择web,choose Module再选择你的项目名就行了,主要的是webapp位置一定要正确,注意图一webapp文件夹的颜色,知道它的特别之处。
4.service层
package com.song.service;
import com.song.Dao.PersonRepository;
import com.song.pojo.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
/**
* 通过姓名查询
* @param name
* @return
*/
public List<Person> findByName(String name){
return personRepository.findByName(name);
}
/**
* 通过地址查询
* @param address
* @return
*/
public List<Person> findByAddress(String address){
return personRepository.findByAddress(address);
}
/**
* 通过姓名和地址查询
* @param name
* @param address
* @return
*/
public List<Person> withNameAndAddressQuery(String name,String address){
return personRepository.withNameAndAddressQuery(name,address);
}
/**
* 删除一行
* @param name
* @return
*/
public int deleteByName(String name){
return personRepository.deleteByName(name);
}
/**
* 新增方法
* @param name
* @param age
* @param address
* @return
*/
public int Add(String name, int age,String address){
return personRepository.Add(name,age,address);
}
/**
* 更改数据库中的一行
* @param id
* @param name
* @return
*/
public int modify(int id,String name){
return personRepository.modify(id,name);
}
}
@Transactional 添加事物管理,不添加的话dao层可能会报错
5.dao层
package com.song.Dao;
import com.song.pojo.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {
// @Query(value = "select * from person p where p.name= ?1", nativeQuery = true)
public List<Person> findByName(String name);
//@Query(value = "select * from person p where p.address= ?1", nativeQuery = true)
public List<Person> findByAddress(String address);
@Query(value = "select p from Person p where p.name=:name and p.address=:address")
public List<Person> withNameAndAddressQuery(@Param("name") String name,@Param("address")String address);
@Modifying
@Query(value = "delete from Person p where p.name= :name")
public int deleteByName(@Param("name") String name);
@Modifying
@Query(value = "insert into person(name,age,address) value(?1,?2,?3)",nativeQuery = true)
public int Add(String name, int age,String address);
@Modifying
@Query(value = "update person set name=?2 where id=?1",nativeQuery = true)
public int modify(int id,String name);
}
重点来了,dao层容易迷惑。
nativeQuery表示使用原生sql语句。占位符格式值得注意。对于正删改这三种方法,最好价格@Modifying的注解。
6.实体类
package com.song.pojo;
import javax.persistence.*;
@Entity
public class Person{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private String name;
private Integer age;
private String 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;
}
public Person() {
}
public Person(Long id, String name, Integer age, String address) {
this.id=id;
this.name = name;
this.age = age;
this.address = address;
}
}
7、Springboot项目启动入口
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* Created by Song on 2017/2/15.
* 项目启动入口,配置包根路径
*/
@SpringBootApplication
@ComponentScan(basePackages = "com.song")
public class Entry {
public static void main(String[] args) throws Exception {
SpringApplication.run(Entry.class, args);
}
}