創建項目:file-->new -->project --->next-->填寫包名、項目名-->選擇相應的模塊和版本-->完成

在生成的pom.xml文件中導入需要的依賴,直接在Maven官網拿。

一、使用jdbcTmplate

         是SpringJDBC的封裝,旨在使JDBC更加易於使用。並且JdbcTemplate處理了資源的建立和釋放。需要配置數據源,但是spring boot已經自動幫我們初始化好了jdbcTemplate對象,並且默認採用tomcat數據源dataSource

 這是所需要的依賴,mysql-connector-java不要使用過高版本,容易出問題。

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在裏面我使用了lombok,lombok是一個可以通過簡單的註解的形式來幫助我們簡化消除一些必須有但顯得很臃腫的 Java 代碼的工具 。效果看後面實體類。如果想要使用lombok,還需要安裝一個插件。file-->Setttings-Plugins

接下來就是配置數據源,在application.properties或者新建一個application.yml中。我是在.yml文件中,看起來有層次感。

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot
    username: root
    password: root

 數據庫建表

 建立對應實體類

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Administrator
 * @description $
 * @date 2019/12/25
 */
@Data   //包含了get,set和toString
@AllArgsConstructor  //生成一個有參構造器
@NoArgsConstructor  //生成一個無參構造器
public class User {
    private Integer userId;
    private String userName;
    private String passWord;
    private String address;
}

dao層(一個接口,一個實現類)

import java.util.List;

public interface UserDaoI {
    public List<User> findAll();
    public User findById(Integer userId);
    public boolean addUser(User user);  
    public boolean deleteById(Integer userId);
    public boolean updateById(Integer userId,String userName);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Administrator
 * @description $
 * @date 2019/12/25
 */
@Repository("userDao")
public class UserDaoImpl implements UserDaoI {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
   /**
    * 功能描述:查詢所有數據
    * @Param: []
    * @Return: java.util.List<com.example.pojo.User>
    * @Author: Administrator
    * @Date: 2019/12/25 17:50
    */
    @Override
    public List<User> findAll() {
        String sql = "SELECT userId,userName,passWord,address from User";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
    }
    /**
     * 功能描述: 由userId查詢數據
     * @Param: [userId]
     * @Return: com.example.pojo.User
     * @Author: Administrator
     * @Date: 2019/12/25 17:50
     */
    @Override
    public User findById(Integer userId) {
        String sql = "select userId,userName,passWord,address from User where userId=?";
        Object[] params = {userId};
        return jdbcTemplate.queryForObject(sql,params,new BeanPropertyRowMapper<User>(User.class));
    }
    /**
     * 功能描述: 添加數據
     * @Param: [user]
     * @Return: boolean
     * @Author: Administrator
     * @Date: 2019/12/25 17:51
     */
    @Override
    public boolean addUser(User user) {
        String sql = "insert into User(userName,passWord,address)values(?,?,?)";
        Object[] params = {user.getUserName(),user.getPassWord(),user.getAddress()};
        return jdbcTemplate.update(sql,params)>0;
    }

    /**
     * 功能描述: 由userId刪除數據
     * @Param: [userId]
     * @Return: boolean
     * @Author: Administrator
     * @Date: 2019/12/25 17:51
     */
    @Override
    public boolean deleteById(Integer userId) {
        String sql = "delete from User where userId=?";
        Object[] params = {userId};
        return jdbcTemplate.update(sql,params)>0;
    }
    /**
     * 功能描述:由userId修改數據
     * @Param: [userId, userName]
     * @Return: boolean
     * @Author: Administrator
     * @Date: 2019/12/25 17:51
     */
    @Override
    public boolean updateById(Integer userId,String userName) {
        String sql = "update User set userName=? where userId=?";
        Object[] params = {userName,userId};
        return jdbcTemplate.update(sql,params)>0;
    }

}

service層

mport org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Administrator
 * @description $
 * @date 2019/12/25
 */
@Service("userService")
public class UserService {
    @Autowired
    @Qualifier("userDao")
    private UserDaoI userDaoI;
    /**
     * 功能描述: <br>
     * 〈〉
     * @Param: []
     * @Return: java.util.List<com.example.pojo.User>
     * @Author: Administrator
     * @Date: 2019/12/25 16:10
     */
    public List<User> findAll(){
        List<User> list = userDaoI.findAll();
        return list;
    }
    
    /**
     * 功能描述: <br>
     * 〈〉
     * @Param: [userId]
     * @Return: com.example.pojo.User
     * @Author: Administrator
     * @Date: 2019/12/25 16:16
     */
    public User findById(Integer userId){
     return userDaoI.findById(userId);
    }

    /**
     * 功能描述: <br>
     * 〈〉
     * @Param: [user]
     * @Return: boolean
     * @Author: Administrator
     * @Date: 2019/12/25 16:26
     */
  
    public boolean add(User user){
        return userDaoI.addUser(user);
    }
   
 
    public boolean deleteById(Integer userId){
        return  userDaoI.deleteById(userId);
    }
    
    public boolean update(Integer userId,String userName){
       return userDaoI.updateById(userId,userName);
    }

}

Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author Administrator
 * @description $
 * @date 2019/12/25
 */
@Controller
public class UserController {
    @Autowired
    @Qualifier("userService")
    private UserService service;

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public String findAll(){
        List<User> list = service.findAll();
        for (User user : list) {
            System.out.println(user.getUserId()+" "+user.getUserName());
        }
        return "查詢所有!";
    }
    @ResponseBody
    @RequestMapping(value = "/this",method = RequestMethod.GET)
    public String findById(Integer userId){
        User user = new User();
        user = service.findById(userId);
        System.out.println(user.getUserId()+" "+user.getUserName());
        return  "傳參查詢";
    }
    @ResponseBody
    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String add(User user){//@ModelAttribute("user") User user
        System.out.println(user.getPassWord()+"接收參數.....");
        boolean flag = service.add(user);
        System.out.println("......"+flag+".....");
        return "添加";
    }
 
    @ResponseBody
    @RequestMapping(value = "/del",method = RequestMethod.GET)
    public String deleteById(Integer userId){
        boolean flag = service.deleteById(userId);
        System.out.println(flag);
        return "根據id刪除";
    }
    @ResponseBody
    @RequestMapping(value = "/update",method = RequestMethod.GET)
    public String update(Integer userId,String userName){
        System.out.println(service.findById(userId).getUserName());
        System.out.println(service.update(userId,userName));
        System.out.println(service.findById(userId).getUserName());
        return "修改數據";
    }

}

 現在就可以進行測試了,在瀏覽器地址欄輸入:localhost:8080/all   看後台是否打印出表中數據(前提是表中有數據),如果想修改端口號8080,可以在屬性文件中配置:server.port=8081。將8080改為8081

在我進行測試的時候順便試了試不同的接收參數方式,一共有如下幾種,有興趣可以試一試

1.通過實體Bean接收請求參數   
    public String login(Student stu, Model model)
2.通過方法的參數接收   
    public String login(String name, String password, Model model)
3.通過HttpServletRequest接收請求參數 
    public String login(HttpServletRequest req,Model model)
4.通過@PathVariable接收URL中的請求參數  
    public String test4(@PathVariable String name)
5.通過@RequestParam接收請求參數 
    public String test5(@RequestParam String name,@RequestParam String passwd)
6.通過@ModelAttribute接收請求參數  
    public String test6(@ModelAttribute("stu") Student stu)

 在上面的代碼中,明顯沒有事務管理,可以使用註解@Transactional

使用方法:在application類添加註解:@EnableTransactionManagement(開啓支持事務),然後在相應的方法或類上註解@Transactional,就這麼簡單。

service層從新寫一個測試方法

    @Transactional
    public void addTest(User user){
        System.out.println("........>");
        userDaoI.addTest(user);
        System.out.println("<........");
       throw new RuntimeException("exception");
    }

但是,默認的只對RuntimeException異常回滾,所以還需要通過屬性進行設置。

指定回滾   @Transactional(rollbackFor=Exception.class)      指定不回滾  @Transactional(noRollbackFor=Exception.class)

還有一些其他屬性:propagation 、isolation、 readOnly 、tlmeoUt 、roIlbackFor 、rollbackForClassName 、noRollbackFor noRollbackForClassName 這些屬性的具體作用就不一一説了。