三、springboot项目的简单使用之:JPA使用操作数据库

来源:互联网 发布:类似origin的软件 编辑:程序博客网 时间:2024/06/03 13:50

一、springboot项目使用JPA操作数据库填删改查

JPA操作数据库与mybatis不同,不需要些xml文件写sql语句去操作数据库。

1、正常编写service接口和实现类。

在dao层类继承JpaRepository类 此类类似mybatis的通用mapper,继承此类就可以使用里面的的通用的操作数据库的方法

JPA代码源码:
//// Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//package org.springframework.data.jpa.repository;import java.io.Serializable;import java.util.List;import org.springframework.data.domain.Example;import org.springframework.data.domain.Sort;import org.springframework.data.repository.NoRepositoryBean;import org.springframework.data.repository.PagingAndSortingRepository;import org.springframework.data.repository.query.QueryByExampleExecutor;@NoRepositoryBeanpublic interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {    List<T> findAll();    List<T> findAll(Sort var1);    List<T> findAll(Iterable<ID> var1);    <S extends T> List<S> save(Iterable<S> var1);    void flush();    <S extends T> S saveAndFlush(S var1);    void deleteInBatch(Iterable<T> var1);    void deleteAllInBatch();    T getOne(ID var1);    <S extends T> List<S> findAll(Example<S> var1);    <S extends T> List<S> findAll(Example<S> var1, Sort var2);



在继承JpaRepository类后面定义要操作的实体对象
JpaRepository<CtiNotifyMember(要操作的实体),String>

2、继承JpaRepository之后使用通用的方法


简单使用:
  @Override    public void addTaskProcess(){        CtiNotifyInfo ctiNotifyInfo=new CtiNotifyInfo();        ctiNotifyInfo.setCaller("50735646,50735641,50735647,50735645");//想通过哪些号码拨打        ctiNotifyInfo.setName("群呼");        ctiNotifyInfo.setWritetime(DateUtil.getServerDate());        ctiNotifyInfo.setSendtime(DateUtil.getServerDate());        Date endtime = new Date(System.currentTimeMillis() + 86400000);        ctiNotifyInfo.setOvertime(endtime);//一般是开始时间的一天之后        ctiNotifyInfo.setNotifymsg("<msg><text><p>col0</p></text></msg>");        ctiNotifyInfo=ctiNotifyInfoRepository.saveAndFlush(ctiNotifyInfo);
}

3、通用JpaRepository在使用中遇到的问题

(1)怎么实现动态插入和更新操作?

@DynamicInsert
@DynamicUpdate


    在实体类上面添加这个两个注解,就能实现动态的插入和更新

(2)动态插入和更新时id不填写时报错,无法使用id的自增功能

报错内容:ids for this class must be manually assigned before calling save(): 

@GeneratedValue(strategy=GenerationType.IDENTITY)
      在id或者需要自增的字段上面声明此注解。就可以产生自增值。

(3)不用写set,get 方法的办法

@Data 此注解需要导入lombok的jar包

(4)实体对应数据库表的内容
       @Table(name = "cti_notifymember", uniqueConstraints = @UniqueConstraint(columnNames = "id"))     指定数据库的表名。和唯一值
  如果缺省@Table注释,系统默认采用类名作为映射表的表名。
  @Entity注释指名这是一个实体Bean
  @Column注释定义了将成员属性映射到关系表中的哪一列和该列的结构信息
  @Id注释指定表的主键,


示例:
@Data@Entity@Table(name = "cti_notifymember", uniqueConstraints = @UniqueConstraint(columnNames = "id"))@DynamicInsert@DynamicUpdatepublic class CtiNotifyMember {    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column cti_notifymember.id     *     * @mbggenerated Sat Jul 01 20:35:07 CST 2017     */    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    @Column(name = "id", unique = false, nullable = false)    private Integer id;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column cti_notifymember.notifyid     *     * @mbggenerated Sat Jul 01 20:35:07 CST 2017     */    @Column(name="notifyid")    private Integer notifyid;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column cti_notifymember.telno     *     * @mbggenerated Sat Jul 01 20:35:07 CST 2017     */    @Column(name="telno")    private String telno;
}


具体参数的详细信息:

@Column注释定义了将成员属性映射到关系表中的哪一列和该列的结构信息,属性如下:

1)name:映射的列名。如:映射tbl_user表的name列,可以在name属性的上面或getName方法上面加入;

2)unique:是否唯一;

3)nullable:是否允许为空;

4)length:对于字符型列,length属性指定列的最大字符长度;

5)insertable:是否允许插入;

6)updatetable:是否允许更新;

7)columnDefinition:定义建表时创建此列的DDL;

8)secondaryTable:从表名。如果此列不建在主表上(默认是主表),该属性定义该列所在从表的名字。

@Id注释指定表的主键,它可以有多种生成方式:

1)TABLE:容器指定用底层的数据表确保唯一;

2)SEQUENCE:使用数据库德SEQUENCE列莱保证唯一(Oracle数据库通过序列来生成唯一ID);

3)IDENTITY:使用数据库的IDENTITY列莱保证唯一;

4)AUTO:由容器挑选一个合适的方式来保证唯一;

5)NONE:容器不负责主键的生成,由程序来完成。

@GeneratedValue注释定义了标识字段生成方式。

@Temporal注释用来指定java.util.Date或java.util.Calender属性与数据库类型date、time或timestamp中的那一种类型进行映射。

@Temporal(value=TemporalType.TIME)


确保这几个注解的使用就能灵活使用JpaRepository的通用方法,但是此类的都是单表的操作。


4、自己手动写操作数据库的方法



代码:
package org.uz.dxt.jpa.dao;import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Modifying;import org.springframework.data.jpa.repository.Query;import org.springframework.stereotype.Repository;import org.springframework.transaction.annotation.Transactional;import org.uz.dxt.jpa.domain.CtiNotityYouzaiInfoAction;import java.util.Date;/** * @author likai * @date 2016年7月4日 */@Repositorypublic interface CtiNotifyYouzaiInfoRepository extends JpaRepository<CtiNotityYouzaiInfoAction, String> {       //普通的sql查询 JPA的 sql操作必须使用@Query注解声明编写 @Query("select a from CtiNotityYouzaiInfoAction a where a.state = 0 and a.userYn = 'Y'")Page<CtiNotityYouzaiInfoAction> findByUserYn(Pageable pageable);
 
//三个参数的更新方法
@Transactional
@Query("update CtiNotityYouzaiInfoAction a set a.state = ?1 , a.updateTime = ?2 where a.dataUuid = ?3")@Modifyingvoid updateByDataUuid(String state, Date updateTime, String dataUuid);}



其他操作以此延伸
原创粉丝点击