zoukankan      html  css  js  c++  java
  • SpringBoot2.x-整合JPA(转发)

    pom.xml配置

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </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-data-jpa</artifactId>
            </dependency>
        </dependencies>

    application.properties配置

    spring.datasource.url=jdbc:mysql://localhost:3306/v_chat?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.username=root
    spring.datasource.password=123456
    
    
    # JPA配置
    spring.jpa.database=mysql
    # 在控制台打印SQL
    spring.jpa.show-sql=true
    # 数据库平台
    spring.jpa.database-platform=mysql
    # 每次启动项目时,数据库初始化策略
    spring.jpa.hibernate.ddl-auto=update
    # 指定默认的存储引擎为InnoDB
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
    #遇到大写字母 加”_”的命名, 驼峰命名
    spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

    番外:

      

    ddl-auto:create----每次运行该程序,没有表格会新建表格,表内有数据会清空
    
    ddl-auto:create-drop----每次程序结束的时候会清空表
    
    ddl-auto:update----每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
    
    ddl-auto:validate----运行程序会校验数据与数据库的字段类型是否相同,不同会报错

    实体类对象

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    /**
     * <pre>
     * User -> 用户实体类
     * </pre>
     *
     * @author 撸小鱼
     * Copyright (c) lofish@foxmail.com
     */
    @Entity(name = "t_user")
    public class User{
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String username;
        private String address;
    
        public Long getId(){
            return id;
        }
    
        public void setId( Long id ){
            this.id = id;
        }
    
        public String getUsername(){
            return username;
        }
    
        public void setUsername( String username ){
            this.username = username;
        }
    
        public String getAddress(){
            return address;
        }
    
        public void setAddress( String address ){
            this.address = address;
        }
    }

    dao接口定义

    import net.lofish.xpra.model.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;
    
    import java.util.List;
    
    /**
     * <pre>
     * UserDao -> dao层
     * </pre>
     *
     * @author 撸小鱼
     * Copyright (c) lofish@foxmail.com
     */
    public interface UserDao extends JpaRepository<User, Long>{
    
        List<User> getUserByAddressEqualsAndIdLessThanEqual( String address, Long id );
        
        //SQL nativeQuery的值是true 执行的时候不用再转化
        @Query( value = "select * from t_user where id=(select max(id) from t_user)", nativeQuery = true )
        User maxIdUser();
    
    }

    测试

    @SpringBootTest
    class SpringbootXpraApplicationTests{
    
    
        @Autowired
        UserDao userDao;
    
    
        @Test
        void contextLoads(){
        }
    
    
        @Test
        void testUserDao(){
            userDao.getUserByAddressEqualsAndIdLessThanEqual( "abc", 1l );
        }
    
    }

    结果

    Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.username as username3_0_ from t_user user0_ where user0_.address=? and user0_.id<=?

    按照规范命名方法, jpa自动转换层对应的查询sql语句

    KeywordSampleJPQL snippet
    And findByLastnameAndFirstname ... where x.lastname = ?1 and x.firstname = ?2
    Or findByLastnameOrFirstname ... where x.lastname = ?1 or x.firstname = ?2
    "Is Equals" "findByFirstname,findByFirstnameIs,findByFirstnameEquals" ... where x.firstname = ?1
    Between findByStartDateBetween ... where x.startDate between ?1 and ?2
    LessThan findByAgeLessThan ... where x.age < ?1
    LessThanEqual findByAgeLessThanEqual ... where x.age <= ?1
    GreaterThan findByAgeGreaterThan ... where x.age > ?1
    GreaterThanEqual findByAgeGreaterThanEqual ... where x.age >= ?1
    After findByStartDateAfter ... where x.startDate > ?1
    Before findByStartDateBefore ... where x.startDate < ?1
    IsNull findByAgeIsNull ... where x.age is null
    "IsNotNull NotNull" findByAge(Is)NotNull ... where x.age not null
    Like findByFirstnameLike ... where x.firstname like ?1
    NotLike findByFirstnameNotLike ... where x.firstname not like ?1
    StartingWith findByFirstnameStartingWith ... where x.firstname like ?1?(parameter bound with appended?%)
    EndingWith findByFirstnameEndingWith ... where x.firstname like ?1?(parameter bound with prepended?%)
    Containing findByFirstnameContaining ... where x.firstname like ?1?(parameter bound wrapped in?%)
    OrderBy findByAgeOrderByLastnameDesc ... where x.age = ?1 order by x.lastname desc
    Not findByLastnameNot ... where x.lastname <> ?1
    In findByAgeIn(Collection<Age> ages) ... where x.age in ?1
    NotIn findByAgeNotIn(Collection<Age> ages) ... where x.age not in ?1
    TRUE findByActiveTrue() ... where x.active = true
    FALSE findByActiveFalse() ... where x.active = false
    IgnoreCase findByFirstnameIgnoreCase ... where UPPER(x.firstame) = UPPER(?1)

    Repository接口

    • CrudRepository 提供CRUD的功能
    • PagingAndSortingRepository 提供分页和排序功能
    • JpaRepository 提供JPA相关的方法,如刷新持久化数据、批量删除
    Spring Data中的每个repository都继承自Repository接口,但是,除此之外,它们每个又有不同的功能

    CrudRepository和PagingAndSortingRepository由Spring Data提供;JpaRepository 由Spring Data JPA提供,而Spring Data JPA又是Spring Data的一个子项目
    ,这就是两者的关系


     
    原文链接:https://segmentfault.com/a/1190000022308656
      
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    CSS改变插入光标颜色caret-color简介及其它变色方法(转)
    Javascript常见性能优化
    安装和使用Karma-Jasmine进行自动化测试
    宝塔 ftp 不能连接 列出时出错
    windows 开机总动运行bat文件
    PHP回调函数--call_user_func_array
    php 获取数组第一个key 第一个键值对 等等
    ssi的使用 开启 配置等
    go get请求 json字符串转为结构体
    php protected 类型如何获取
  • 原文地址:https://www.cnblogs.com/name-lizonglin/p/14409031.html
Copyright © 2011-2022 走看看