好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Springboot+hibernate实现简单的增删改查示例

1、创建好项目之后在 配置端口号(也可以不用配置,默认端口8080)

?

1

2

3

#server

server.port= 8080

server.tomcat.uri-encoding=utf- 8

2、配置mysql

?

1

2

3

4

5

#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以及视图层

?

1

2

3

4

5

6

7

8

9

10

11

12

13

#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需要的依赖

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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所在包下面,不然找不到路径

以上这篇springboot+hibernate实现简单的 增删改查 示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://www.cnblogs.com/NCL--/p/8539288.html

查看更多关于Springboot+hibernate实现简单的增删改查示例的详细内容...

  阅读:41次