Posts

Showing posts with the label hibernate

@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

Save vs persist

Save nó sẽ trả về một đối tượng đã chèn vào Persist nó sẽ không trả về Điểm chung của cả 2 là đều đẩy một đối tượng vào trạng thái Persistence

Hàm update() và merge() trong hibernate

1. Đơn giản nhất Hãy hiểu về hàm update như ý nghĩa của cái tên đó là update một cái gì đó ( đó chính là một đối tượng có giá trị ID rõ ràng) ví dụ: Session session = factory . openSession ( ) ; Transaction tx = session . beginTransaction ( ) ; Student student = new Student ( ) ; student . setId ( 111 ) ; student . setName ( "chandra shekhar" ) ; student . setRollNumber ( 8469 ) ; session . update ( student ) ; tx . commit ( ) ; session . close ( ) ; Đoạn code trên chạy đẹp do là đối tượng đã được thiết lập ID. Quá đơn giản Nếu ID k có trong DB là lỗi ngay Và nó là lý do sinh ra hàm saveOrUpdate(); :-))) 2. Một chút phức tạp  Trường hợp này đối tượng được load hoặc get, findxxx,.... từ DB Session session = factory . openSession ( ) ; Transaction tx = session . beginTransaction ( ) ; Student student = session . load ( Student . class , 111 ) ;...

data.sql and schema.sql in springboot

@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

EntityManager in Java EE

Managing Entities Entities are managed by the entity manager, which is represented by  javax.persistence.EntityManager  instances. Each  EntityManager  instance is associated with a persistence context: a set of managed entity instances that exist in a particular data store. A persistence context defines the scope under which particular entity instances are created, persisted, and removed. The  EntityManager  interface defines the methods that are used to interact with the persistence context. The  EntityManager  Interface The  EntityManager  API creates and removes persistent entity instances, finds entities by the entity’s primary key, and allows queries to be run on entities. Container-Managed Entity Managers With a  container-managed entity manager , an  EntityManager  instance’s persistence context is automatically propagated by the container to all application components that use the  EntityManager ...

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...

Relationship in Hibernate

Will be soon :-)

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...