Java中部分注解简介
@MappedSuperclass :实体类继承映射超类
抽象类或具体的类都可以作为映射超类,使用@MappedSuperclass注解来指定映射超类
package com.mikan;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class Employee implements Serializable {
private static final long serialVersionUID = -7674269980281525370L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer empId;
@Column
protected String name;
// getter/setter方法
}
package com.mikan;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "FT_EMP")
public class FullTimeEmployee extends Employee {
private static final long serialVersionUID = 9115429216382631425L;
// 继承映射超类的empId和name属性
@Column
private Double salary;
// getter/setter方法
}
package com.mikan;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "PT_EMP")
public class PartTimeEmployee extends Employee {
private static final long serialVersionUID = -6122347374515830424L;
// 继承映射超类的empId和name属性
@Column(name = "hourly_wage")
private Float hourlyWage;
// getter/setter方法
}
映射超类能够像实体类一样被映射,只是它的映射将作用于继承自它的实体类,因为它本身不存在单独的表。当作用于子类时,继承的映射信息将作用于子类对应的表上。
参考https://blog.csdn.net/mhmyqn/article/details/37994707
@Data: lombok代替setter getter等方法
@Entity :指出该Java类为实体类,将映射到指定的数据库
@Transient :忽略该属性,不需要映射到数据表的一列,否则默认为@Basic
@Temporal :在属性上调整精度,比如Date
@Table :标注常用name属性,用于指定数据库的表明
@Id :映射主键(放在getter方法之前)
@GeneratedValue :用于标注主键的生成策略,通过strategy属性指定
@Column :映射数据表的列名,指定unique,length等
@Basic :基本注解,默认有
单向多对一:使用@ManyToOne来映射多对一关系映射;使用@JoinColumn来映射外键;建议先保存1的一端,后保存n的一端;可以使用@ManyToOne的fetch来修改默 认的关联属性的加载策略
单向一对多:使用@OneToMany来映射一对多关系映射;使用@JoinColumn来映射外键;
双向一对一:使用@OneToOne来映射一对一对应关系映射;建议先保存不维护关联关系的一方,既没有外键的一方,
双向多对多:使用@ManyToMany来映射多对多关系映射;使用@JoinTable来映射中间表;name:指定外键的列名;rederenedColumnName:指定外键列关联的当期表 的那一列;inverseJoinColumns:映射关联的类所在中间表的外键
JPA简单用法
建一个接口继承org.springframework.data.jpa.repository.JpaRepository
示例:
public interface AdvertisementDao extends JpaRepository<Advertisement, Long> {
}
jpa默认查询方法
1.findOne(id):查询指定id的数据
2.List<T> findAll():查询对应实体的所有数据
3.List<T> findAll(Sort sort):带排序的查询
Sort(Direction.DESC,String properties),Direction指定排序方式,properties指 定排序的字段;Sort(Direction direction, List<String> properties)
1.T save(entity):新增数据/更新数据
2.Page<T> findAll(Pageable pageable):带分页的查询
PageRequest(int page, int size),page代表页码,size代表每页显示的条数
PageRequest(int page, int size, Sort sort)
1.T save(list):批量新增
2.void flush:将所有挂起的更改同步到数据库
3.T saveAndFlush(entity):更新数据
4.void delete(id):删除指定id数据
5.void delete(entity):删除数据
6.void delete(list):删除list集合
7.void deleteAll:删除所有数据
8.exists(id):是否存在指定id的数据
9.count():统计数据数目
jpa自定义简单查询
关键字 | 示例 | 原生sql |
---|---|---|
And | findByLastnameAndFirstname | …where x.lastname=?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | …where x.lastname = ?1 or x.firstname = ?2 |
Is, Equals | 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 ages) | …where x.age in ?1 |
NotIn | findByAgeNotIn(Collection age) | …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) |
自定义SQL查询
在SQL的查询方法上面使用@Query注解,如涉及到删除和修改在需要加上@Modifying.也可以根据需要添加 @Transactional 对事务的支持
public interface TopicInviteeDao extends JpaRepository<TopicInvitee, Long> {
@Query(nativeQuery = true, value = "SELECT * FROM t_topic_invitee WHERE t_topic_invitee.topic_id =?1 AND t_topic_invitee.user_id =?2")
TopicInvitee findByTopicIdAndUserId(Long topicId, Long userId);
@Query(nativeQuery = true, value = "SELECT * FROM t_topic_invitee WHERE t_topic_invitee.topic_id =?1 ")
List<TopicInvitee> findByTopicId(Long topicId);
List<TopicInvitee> findByUserId(Long userId);
@Query(nativeQuery = true, value = "SELECT * FROM t_topic_invitee WHERE t_topic_invitee.user_id =?1 ")
List<TopicInvitee> findAllByUserId(Long userId);
@Transactional
@Modifying
@Query(nativeQuery = true, value = "DELETE FROM t_topic_invitee WHERE t_topic_invitee.topic_id =?1 ")
int deleteByTopic(Long topicId);
}