logo
Tags down

shadow

How to replicate INSERT/UPDATE/DELETE statements using JPA and Hibernate


By : venkatesh
Date : October 14 2020, 02:21 PM
I wish this helpful for you
This was a very interesting question, so I decided to turn this answer into a full-blown article.
code :
CREATE TABLE old_post (
    id int8 NOT NULL,
    title varchar(255),
    version int4 NOT NULL,
    PRIMARY KEY (id)
)

CREATE TABLE post (
    id int8 NOT NULL,
    created_on date, 
    title varchar(255),
    version int4 NOT NULL,
    PRIMARY KEY (id)
)
@Entity(name = "Post")
@Table(name = "post")
public static class Post {

    @Id
    private Long id;

    private String title;

    @Column(name = "created_on")
    private LocalDate createdOn = LocalDate.now();

    @Version
    private int version;

    //Getters and setters omitted for brevity
}
public class ReplicationInsertEventListener 
        implements PostInsertEventListener {

    public static final ReplicationInsertEventListener INSTANCE = 
        new ReplicationInsertEventListener();

    @Override
    public void onPostInsert(
            PostInsertEvent event) 
            throws HibernateException {
        final Object entity = event.getEntity();

        if(entity instanceof Post) {
            Post post = (Post) entity;

            event.getSession().createNativeQuery(
                "INSERT INTO old_post (id, title, version) " +
                "VALUES (:id, :title, :version)")
            .setParameter("id", post.getId())
            .setParameter("title", post.getTitle())
            .setParameter("version", post.getVersion())
            .setFlushMode(FlushMode.MANUAL)
            .executeUpdate();
        }
    }

    @Override
    public boolean requiresPostCommitHanding(
            EntityPersister persister) {
        return false;
    }
}

public class ReplicationUpdateEventListener 
    implements PostUpdateEventListener {

    public static final ReplicationUpdateEventListener INSTANCE = 
        new ReplicationUpdateEventListener();

    @Override
    public void onPostUpdate(
            PostUpdateEvent event) {
        final Object entity = event.getEntity();

        if(entity instanceof Post) {
            Post post = (Post) entity;

            event.getSession().createNativeQuery(
                "UPDATE old_post " +
                "SET title = :title, version = :version " +
                "WHERE id = :id")
            .setParameter("id", post.getId())
            .setParameter("title", post.getTitle())
            .setParameter("version", post.getVersion())
            .setFlushMode(FlushMode.MANUAL)
            .executeUpdate();
        }
    }

    @Override
    public boolean requiresPostCommitHanding(
            EntityPersister persister) {
        return false;
    }
}

public class ReplicationDeleteEventListener 
        implements PreDeleteEventListener {

    public static final ReplicationDeleteEventListener INSTANCE = 
        new ReplicationDeleteEventListener();

    @Override
    public boolean onPreDelete(
            PreDeleteEvent event) {
        final Object entity = event.getEntity();

        if(entity instanceof Post) {
            Post post = (Post) entity;

            event.getSession().createNativeQuery(
                "DELETE FROM old_post " +
                "WHERE id = :id")
            .setParameter("id", post.getId())
            .setFlushMode(FlushMode.MANUAL)
            .executeUpdate();
        }

        return false;
    }
}
public class ReplicationEventListenerIntegrator 
        implements Integrator {

    public static final ReplicationEventListenerIntegrator INSTANCE = 
        new ReplicationEventListenerIntegrator();

    @Override
    public void integrate(
            Metadata metadata,
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {

        final EventListenerRegistry eventListenerRegistry =
                serviceRegistry.getService(EventListenerRegistry.class);

        eventListenerRegistry.appendListeners(
            EventType.POST_INSERT, 
            ReplicationInsertEventListener.INSTANCE
        );

        eventListenerRegistry.appendListeners(
            EventType.POST_UPDATE, 
            ReplicationUpdateEventListener.INSTANCE
        );

        eventListenerRegistry.appendListeners(
            EventType.PRE_DELETE, 
            ReplicationDeleteEventListener.INSTANCE
        );
    }

    @Override
    public void disintegrate(
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {

    }
}
<property name="hibernate.integrator_provider"
          value="com.vladmihalcea.book.hpjp.hibernate.listener.ReplicationEventListenerIntegrator "/>
Post post1 = new Post();
post1.setId(1L);
post1.setTitle(
    "The High-Performance Java Persistence book is to be released!"
);

entityManager.persist(post1);
Query:["INSERT INTO old_post (id, title, version) VALUES (?, ?, ?)"], Params:[(1, The High-Performance Java Persistence book is to be released!, 0)]

Query:["insert into post (created_on, title, version, id) values (?, ?, ?, ?)"], Params:[(2018-12-12, The High-Performance Java Persistence book is to be released!, 0, 1)]
Post post1 = entityManager.find(Post.class, 1L);
post1.setTitle(post1.getTitle().replace("to be ", ""));

Post post2 = new Post();
post2.setId(2L);
post2.setTitle(
    "The High-Performance Java Persistence book is awesome!"
);

entityManager.persist(post2);
 Query:["select tablerepli0_.id as id1_1_0_, tablerepli0_.created_on as created_2_1_0_, tablerepli0_.title as title3_1_0_, tablerepli0_.version as version4_1_0_ from post tablerepli0_ where tablerepli0_.id=?"], Params:[(1)]

 Query:["INSERT INTO old_post (id, title, version) VALUES (?, ?, ?)"], Params:[(2, The High-Performance Java Persistence book is awesome!, 0)]

 Query:["insert into post (created_on, title, version, id) values (?, ?, ?, ?)"], Params:[(2018-12-12, The High-Performance Java Persistence book is awesome!, 0, 2)]

 Query:["update post set created_on=?, title=?, version=? where id=? and version=?"], Params:[(2018-12-12, The High-Performance Java Persistence book is released!, 1, 1, 0)]

 Query:["UPDATE old_post SET title = ?, version = ? WHERE id = ?"], Params:[(The High-Performance Java Persistence book is released!, 1, 1)]
Post post1 = entityManager.getReference(Post.class, 1L);
entityManager.remove(post1);
Query:["DELETE FROM old_post WHERE id = ?"], Params:[(1)]
Query:["delete from post where id=? and version=?"], Params:[(1, 1)]


Share : facebook icon twitter icon

Hibernate: Update an object -> also unwanted delete statements are performed


By : Mikdam Mik
Date : March 29 2020, 07:55 AM
may help you . This means (as you suggested) that your collection is empty. But it's not due to lazy-loading - the debugger would allow you to load the collection. Perhaps it is empty for another reason. Confirm this by showing collection.size().
The other part of the issue is the cascade. If you have defined to cascade delete-orphan, then either remove it, or make sure the collection is actually filled.

can Hibernate emit MERGE SQL statements for INSERT/UPDATE constructs?


By : Luke Carroll
Date : March 29 2020, 07:55 AM
wish of those help there is session.merge() which does basicly the same using standard sql selects to determine if it is there or not. It has therefor 2 roundtrips but is supported across all sqldatabases.

firebird MON$STATEMENTS insert, delete, update


By : chuables
Date : March 29 2020, 07:55 AM
This might help you MON$STATE = 1 means that a query being executed right now. MON$STATE = 0 means that a SELECT query has been executed and is in a suspended state. i.e. either waits for a row being fetched by a client application or an end of a record set is reached but query is not closed yet.
INSERT, UPDATE, DELETE queries don't have a SUSPENDED state. They are either running or finished and gone.

Spring Boot 2.1.2, Hibernate 5: Register Hibernate Event Listeners (Insert/Update/Delete)


By : user2669849
Date : March 29 2020, 07:55 AM
it helps some times I found the solution on Bozho's blog, the code can stay mostly the same as before, but I can't autwire SessionFactory anymore: I have to autowire EntityManagerFactory instead, and then "unwrap" it as SessinFactoryImpl sf = emf.unwrap(..). That's the only change.
Latest code: Configuration:
code :
@Component   
public class HibernateEntityEventListenerConfig {



@PersistenceUnit
private EntityManagerFactory emf;  // NOTE Can't autowire SessionFactory.

@Autowired
private HibernateEntityEventListener entityEventListener;

@PostConstruct
public void registerListeners() {
    // NOTE the emf.unwrap() to get the SessionFactoryImpl
    SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory)
                .getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener((PreInsertEventListener) entityEventListener);
        registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener((PreUpdateEventListener) entityEventListener);
        registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener((PreDeleteEventListener) entityEventListener);
}

}

Are Cursors used for INSERT, UPDATE and DELETE statements?


By : Swapnil Patil
Date : March 29 2020, 07:55 AM
I wish this helpful for you Almost every statement has to create/open a cursor (even DDL statements). A cursor is a pointer to a private SQL area that stores information about the processing of a SELECT or data manipulation language (DML) statement (INSERT, UPDATE, DELETE, or MERGE).
If you don't create an explicit cursor then an implicit cursor is used. The most useful and most-used attribute of an implicit cursor is the %ROWCOUNT attribute, it returns the number of affected rows.
Related Posts Related Posts :
  • How to specify which version of a concrete implementation for an abstract class to autowire in Spring?
  • Regular expression get the third element from a string
  • How do I use client certificates in a client java application?
  • Allow dashes in email validations
  • Unable to display Json data
  • Add constraints to lines in javaFX
  • How do you include a classpath wildcard as an argument to a java bash call?
  • How to use classes from one project on another project in java?
  • How to parse a column that has a custom json format from a spark DataFrame
  • How to parse entire DOM elements and follow changes in DOM using selenium webdriver in java
  • java set object field equal another field upon instantation
  • Java Threads Object Lock
  • Euro Currency getting Question mark?
  • Running out of pools using CompleteableFuture and Spring Transaction
  • Drools can not use a generic type for a function's parameter in DRL
  • Create a new ArrayList with all the elements of another ArrayList except one in one line of code
  • log4j could not create log file in spring boot resti api
  • Android BLE discovery issue
  • Adding Java final keyword to working method that builds instances inside a loop
  • Using Java Streams to group together a List of objects by an attribute and reduce them to a new list of object with the
  • Java - Sort - Variable comparator
  • Parse xml file, rename tag and save it again
  • My pig dice game in JAVA won't save each player's score and the game doesn't stop even after reaching the score
  • is unsafe to copy a three-dimensional array using Arraylist?
  • Whitelabel Error Page instead of specific jsp page
  • Java. Remove a row from a matrix (array)
  • Trying to use listFiles() function, but array of files is empty, Java, Andriod Studio
  • Continue sleeping for remaining time when thread is interrupted
  • Android Studio SQLite database creation does not work?
  • Exporting a lazily initialized bean (which implements SelfNaming and is annotated with ManagedResource annotation) gives
  • Java Regex OR operator not working properly
  • "Invalid classification data: expect label value"
  • Intent .putExtra return null with PendingIntent
  • Draw shapes on scrollable JPanel
  • Can't connect to redis from spring inside docker container
  • Display base64-encoded image
  • Android cardview, change background color with switch listener
  • Multiple classpaths when running Ant taskdef?
  • Disabling sound on Android's Ongoing notification updating
  • ChartPanel not registering as a component in a GUI
  • Spring @Configuration not overriden in test context
  • How can i solve duplication of code in this?
  • Method undefined for object in java cannot be compiled and deployed
  • Peek at a value from an array with a probabilistic quantity
  • java - how to limit operation(e.g login) by cowndown timer
  • How can I search informations from file with names using input (java)?
  • 'Gradle cucumber' With testImplementation Not Working
  • Log4j2/Slf4j and Java 11
  • Subclasses with Java 8 lambdas and Optional
  • Optaplanner - Drools rules List<> memberOf List<>?
  • Problem with sending keys to a form field when there is no submit button available
  • Does anyone know how to add a value to org.w3c.dom.Element to instantiate both MiningSchema and SupportVectorMachineMode
  • Is it possible to use a different Spring Batch Sequence than the default one?
  • Java derby embedded DB error: The syntax of the string representation of a date/time value is incorrect
  • WeakReference of a Collection in java
  • Getting an average of doubles from ArrayList
  • Detecting circular references in Directed acyclic graph
  • Unexpected behavior sending object through socket in java
  • null object reference on data binding
  • Why am I getting an ArrayIndexOutOfBoundsException in this particular code?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org