Posts

Showing posts with the label jpa

JPA useful

Table 3. Supported keywords inside method names Keyword Sample JPQL 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 find...

JOIN vs JOIN FETCH in JPA hibernate

Ví dụ bạn có một Student Entity và một Country entity trong Student entity có một khóa ngoại tới Country entity JOIN khi dùng thì nó tương tự như câu lệnh JOIN trong SQL, nhưng khi Đối tượng Student được trả về thì nó sẽ hoặc load cả Country entity hoặc là không load Contry(Nếu bạn để là Lazy thì nó sẽ k load Country còn nếu để là Eager thì nó sẽ load Country) do đó khi bạn dùng student.getCountry() nó có thể trả về Null hoặc là lỗi. Còn nếu bạn dùng JOIN Fetch khi load Student Join fetch với Country thì nó sẽ load cả đối tượng Contry bất kể bạn để load là Lazy hay là Eager vì vậy bạn có thể dùng student.getCountry().getName() là có giá trị

@Lob in JPA, Hibernate

http://www.java2s.com/Tutorials/Java/JPA/0250__JPA_Lob_Column.htm The following code shows how to save byte array to database with @Lob annotation. LOBs have two types in the database: character large objects, called CLOBs, and binary large objects, or BLOBs. A CLOB column holds a large character sequence, and a BLOB column can store a large byte sequence. The Java types mapped to BLOB columns are byte[] Byte[] , and Serializable types, while char[] Character[] , and String objects are mapped to CLOB columns. @Lob private byte[] picture; //BLOB or @Lob private Byte[] picture; //BLOB @Lob private char [] picture; // CLOB or @Lob private Character[] picture; //CLOB

@idclass vs @embedable

1. @Idclass @Entity @IdClass(ProjectId.class) public class Project {     @Id int departmentId;     @Id long projectId;      : } Class ProjectId {     int departmentId;     long projectId; } 2.@embedable @Entity public class Project {     @EmbeddedId ProjectId id;      : } @Embeddable Class ProjectId {     int departmentId;     long projectId; } Ref: https://www.objectdb.com/java/jpa/entity/id

Pessimistic Locking in JPA

PESSIMISTIC_READ – allows us to obtain a shared lock and prevent the data from being updated or deleted, Whenever we want to just read data and don’t encounter dirty reads, we could use PESSIMISTIC_READ (shared lock). We won’t be able to make any updates or deletes though. It sometimes happens that the database we use doesn’t support the PESSIMISTIC_READ lock, so it’s possible that we obtain the PESSIMISTIC_WRITE lock instead. PESSIMISTIC_WRITE – allows us to obtain an exclusive lock and prevent the data from being read, updated or deleted, Any transaction that needs to acquire a lock on data and make changes to it should obtain the PESSIMISTIC_WRITE lock. According to the JPA specification, holding PESSIMISTIC_WRITE lock will prevent other transactions from reading, updating or deleting the data. Please note that some database systems implement multi-version concurrency control which allows readers to fetch data that has been already blocked. entityManager.find(St...

Optimistic locking in JPA Hibernate with a best simple way

Step 1: Remember this annotation  @Version  @Column(name="OPTLOCK")   private long version; Think of it, add it to the Model @Entity or @Table which you want to apply  @Entity public class Employee{   private @Id   @GeneratedValue   Long id;   private String name;   private String dept;   private int salary;   @Version   private long version;     ............. } So everything is done Step 2: Get detail in  plenty of optimistic locking https://www.logicbig.com/tutorials/spring-framework/spring-data/optimistic-lock.html https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/locking/Locking.html http://docs.jboss.org/hibernate/orm/6.0/userguide/html_single/Hibernate_User_Guide.html#locking-optimistic

Pagination and Sorting in SpringBoot RESTful Web Services

Follow this tutorial http://appsdeveloperblog.com/rest-pagination-tutorial-with-spring-mvc/ https://dzone.com/articles/conditional-pagination-and-sorting-using-restful-w Step 1: Dao Layer extends  PagingAndSortingRepository @Repository public interface PaginationDao extends PagingAndSortingRepository<PagingEntity, Integer> { } Step 2: Service Layer  @Service public class PaginationService { @Autowired private PaginationDao paginationDao; public Page findJsonDataByCondition(String orderBy, String direction, int page, int size) { Sort sort = null; if (direction.equals("ASC")) { sort = new Sort(new Sort.Order(Direction.ASC, orderBy)); } if (direction.equals("DESC")) { sort = new Sort(new Sort.Order(Direction.DESC, orderBy)); } Pageable pageable = new PageRequest(page, size, sort); Page data = paginationDao.findAll(pageable); return data; } } Step 3: Controller layer @RestController @RequestMapping(value = "/p...

orphanRemoval vs CascadeType.REMOVE in JPA

In JPA, both orphanRemoval and CascadeType.REMOVE are used to manage the lifecycle of child entities in a parent-child relationship, but they differ in their behavior. 1. orphanRemoval = true When orphanRemoval is set to true , the child entity is removed when it is no longer referenced by the parent entity. The parent entity doesn’t necessarily have to be removed for this to happen. This is useful when you want to automatically delete a child entity if it is no longer associated with a parent entity. Example: @Entity public class Parent { @OneToMany (mappedBy = "parent" , orphanRemoval = true ) private List<Child> children = new ArrayList<>(); // setters and getters } @Entity public class Child { @ManyToOne private Parent parent ; // setters and getters } Behavior: If you do parent.setChild(null); and then entity.save(parent); , the child entity will be deleted, as it is no longer referenced by the parent. 2. CascadeType.REMOVE Casc...