【JPA】Springboot+jpa簡單的增刪改查

Springboot+hibernate簡單的增刪改查

1、創建好項目之後在配置端口號(也可以不用配置,默認端口8080)

 

#server
server.port=8080
server.tomcat.uri-encoding=utf-8

2、配置mysql

#MySQL
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
spring.datasource.username=*****
spring.datasource.password=*****
3、配置jpa以及視圖層
#Spring Data JPA
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
spring.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

#視圖層控制
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**
4、在pom中加入springboot需要的依賴
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>1.4.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
<!--        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>1.4.3.RELEASE</version>
        </dependency>-->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.46</version>
        </dependency>


    </dependencies>
整個包結構

Controller

package com.song.configuration.controller;

import com.alibaba.fastjson.JSONObject;
import com.song.configuration.entity.User;
import com.song.configuration.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 
 * User控制層
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index")
    public String index(){
        return "user/index";
    }

    @RequestMapping(value = "/show",method = RequestMethod.GET)
    @ResponseBody
    public String show(@RequestParam(value = "name")String name){
        User user = userService.findUserByName(name);
        if(null != user)
            return user.getId()+"/"+user.getName()+"/"+user.getPassword();
        else return "null";
    }

    @RequestMapping("/showlist")
    @ResponseBody
   public JSONObject showList(){
        List<User> list = userService.find();
       JSONObject jo = new JSONObject();
        if(list!=null){

            jo.put("code",0);
            jo.put("msg",true);
            jo.put("count",list.size());
            jo.put("data",list);
        }
       return jo;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String  deleteUserById(@RequestParam(value = "id")Integer id){
       return  userService.deleteUserById(id);
    }

    @RequestMapping("/update")
    @ResponseBody
    public String queryUserById(@RequestParam(value = "id")Integer id,@RequestParam(value = "name")String  name){

        return userService.queryUserById(id,name);
    }

    @RequestMapping("/add")
    @ResponseBody
    public String countUserBy(@RequestParam(value = "id")Integer id,@RequestParam(value = "name")String name,@RequestParam(value = "password")String  password){
        return userService.countUserBy(id,name,password);
    }
}
service
package com.song.configuration.service;

import com.song.configuration.entity.User;
import com.song.configuration.repository.UserRepositoty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 
 * User業務邏輯
 */
@Service
public class UserService {
    @Autowired
    private UserRepositoty userRepositoty;

    public User findUserByName(String name) {
        User user = null;
        try {
            user = userRepositoty.findByUserName(name);
        } catch (Exception e) {
        }
        return user;
    }

    public List<User> find() {
        List<User> list = null;
        try {
            list = userRepositoty.find();
        } catch (Exception e) {
        }
        return list;
    }

    public String deleteUserById(Integer id){
        int  a = userRepositoty.deleteUserById(id);
        return "chenggong";
    }

    public String queryUserById(Integer id ,String name){
        int a = userRepositoty.queryUserById(id,name);
        return "成功";
    }

    public String countUserBy(Integer id ,String name ,String password){
        int a = userRepositoty.countUserBy(id,name,password);
        return "成功";
    }
}

 

Repository

 

package com.song.configuration.repository;

import com.song.configuration.entity.User;
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 org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Song on 2017/2/15.
 * User表操作接口
 */
@Repository
public interface UserRepositoty extends JpaRepository<User,Long>{
    /*
    * 根據用戶名查詢
    * */
    @Query("select t from User t where t.name = :name")
    User findByUserName(@Param("name") String name);

    /*
    * 查詢全部
    * */
    @Query("select t from User t")
    List<User> find();

    /*
    * 刪除  必須加入@Modifying和@Transactional
    * */
    @Modifying
    @Transactional
    @Query("delete from User u where u.id=:id")
    public int deleteUserById(@Param("id") Integer id);


    @Modifying
    @Transactional
    @Query("update User u set u.name = :name where u.id=:id")
    public int queryUserById(@Param("id") Integer id,@Param("name") String name);
    
    @Query(value = "insert into User value(?,?,?)", nativeQuery = true)
    @Transactional
  @Modifying
    public int countUserBy(@Param("id")Integer id,@Param("name") String name,@Param("password") String password);
}

 

@modifying:

(1)可以通過自定義的 JPQL 完成 UPDATE 和 DELETE 操作。
注意: JPQL 不支持使用 INSERT;
(2)在 @Query 註解中編寫 JPQL 語句, 但必須使用 @Modifying 進行修飾. 以通知   SpringData, 這是一個 UPDATE 或 DELETE 操作 
(3)UPDATE 或 DELETE 操作需要使用事務,此時需要定義 Service 層,在 Service 層的方法上添加事務操作; 
(4)默認情況下, SpringData 的每個方法上有事務, 但都是一個只讀事務。

@Transactional:

A. 一個功能是否要事務,必須納入設計、編碼考慮。不能僅僅完成了基本功能就ok。
B. 如果加了事務,必須做好開發環境測試(測試環境也儘量觸發異常、測試回滾),確保事務生效。
C. 以下列了事務使用過程的注意事項,請大家留意。
1. 不要在接口上聲明@Transactional ,而要在具體類的方法上使用 @Transactional 註解,否則註解可能無效。
2.不要圖省事,將@Transactional放置在類級的聲明中,放在類聲明,會使得所有方法都有事務。故@Transactional應該放在方法級別,不需要使用事務的方法,就不要放置事務,比如查詢方法。否則對性能是有影響的。
3.使用了@Transactional的方法,對同一個類裏面的方法調用, @Transactional無效。比如有一個類Test,它的一個方法A,A再調用Test本類的方法B(不管B是否public還是private),但A沒有聲明註解事務,而B有。則外部調用A之後,B的事務是不會起作用的。(經常在這裏出錯)
4.使用了@Transactional的方法,只能是public,@Transactional註解的方法都是被外部其他類調用纔有效,故只能是public。道理和上面的有關聯。故在 protected、private 或者 package-visible 的方法上使用 @Transactional 註解,它也不會報錯,但事務無效。
5.經過在ICORE-CLAIM中測試,效果如下:
A.拋出受查異常XXXException,事務會回滾。
B.拋出運行時異常NullPointerException,事務會回滾。
C.Quartz中,execute直接調用加了@Transactional方法,可以回滾;間接調用,不會回滾。(即上文3點提到的)
D.異步任務中,execute直接調用加了@Transactional方法,可以回滾;間接調用,不會回滾。(即上文3點提到的)
E.在action中加上@Transactional,不會回滾。切記不要在action中加上事務。
F.在service中加上@Transactional,如果是action直接調該方法,會回滾,如果是間接調,不會回滾。(即上文3提到的)
G.在service中的private加上@Transactional,事務不會回滾。

application:

package com.song.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * 
 * 項目啓動入口,配置包根路徑
 */
@SpringBootApplication
@ComponentScan(basePackages = "com.song.configuration")
public class Entry {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Entry.class, args);
    }
}

 

Jpaconfiguration:

package com.song.configuration;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.song.configuration.repository")
@EntityScan(basePackages = "com.song.configuration.entity")
public class JpaConfiguration {
    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

其他包要在jpaconfiguration所在包下面,不然找不到路徑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章