Session.bySimpleNaturalId getReference

package org.example.demo.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.NaturalId;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;

public class Test {
    public static void main(String[] args) {
        ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .applySetting("hibernate.connection.url", "jdbc:p6spy:postgresql://localhost:5432/test")
                .applySetting("hibernate.connection.username", "postgres")
                .applySetting("hibernate.connection.password", "postgres")
                .applySetting("hibernate.hbm2ddl.auto", "create").build();
        Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClass(Book.class).getMetadataBuilder()
                .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();
        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
        Session session = sessionFactory.openSession();

        session.beginTransaction();
        Book book = new Book();
        book.title = "测试书";
        String isbn = "978";
        book.isbn = isbn;
        session.persist(book);
        session.getTransaction().commit();

        session.clear();

        Book b = session.bySimpleNaturalId(Book.class).getReference(isbn);
        // class org.example.demo.hibernate.Test$Book_$$_jvst545_0
        System.out.println(b.getClass());
        // 如果没有下面这句,则不会有第二个查询
        // org.example.demo.hibernate.Test$Book@6e0ff644
        System.out.println(b);

        session.close();
        sessionFactory.close();
    }

    @Entity(name = "Book")
    public static class Book {
        @Id
        @GeneratedValue
        Integer id;
        String title;
        @NaturalId
        String isbn;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getIsbn() {
            return isbn;
        }

        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }
    }
}

生成的 SQL

drop table if exists Book cascade
drop sequence if exists hibernate_sequence

create sequence hibernate_sequence start 1 increment 1
create table Book (id int4 not null, isbn varchar(255), title varchar(255), primary key (id))
alter table Book add constraint UK_u31e1frmjp9mxf8k8tmp990i unique (isbn)
select nextval ('hibernate_sequence')
insert into Book (isbn, title, id) values ('978', '测试书', 1)

select test_book_.id as id1_0_ from Book test_book_ where test_book_.isbn='978'
select test_book0_.id as id1_0_0_, test_book0_.isbn as isbn2_0_0_, test_book0_.title as title3_0_0_ from Book test_book0_ where test_book0_.id=1

Session.byNaturalId load

package org.example.demo.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.NaturalId;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;

public class Test {
    public static void main(String[] args) {
        ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .applySetting("hibernate.connection.url", "jdbc:p6spy:postgresql://localhost:5432/test")
                .applySetting("hibernate.connection.username", "postgres")
                .applySetting("hibernate.connection.password", "postgres")
                .applySetting("hibernate.hbm2ddl.auto", "create").build();
        Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClass(Book.class).getMetadataBuilder()
                .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();
        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
        Session session = sessionFactory.openSession();

        session.beginTransaction();
        Book book = new Book();
        book.title = "测试书";
        String isbn = "978";
        book.isbn = isbn;
        session.persist(book);
        session.getTransaction().commit();

        session.clear();

        Book b = session.byNaturalId(Book.class).using("isbn", isbn).load();
        // class org.example.demo.hibernate.Test$Book
        System.out.println(b.getClass());
        // org.example.demo.hibernate.Test$Book@1b39fd82
        System.out.println(b);

        session.close();
        sessionFactory.close();
    }

    @Entity(name = "Book")
    public static class Book {
        @Id
        @GeneratedValue
        Integer id;
        String title;
        @NaturalId
        String isbn;
    }
}

生成的 SQL

drop table if exists Book cascade
drop sequence if exists hibernate_sequence

create sequence hibernate_sequence start 1 increment 1
create table Book (id int4 not null, isbn varchar(255), title varchar(255), primary key (id))
alter table Book add constraint UK_u31e1frmjp9mxf8k8tmp990i unique (isbn)
select nextval ('hibernate_sequence')
insert into Book (isbn, title, id) values ('978', '测试书', 1)

select test_book_.id as id1_0_ from Book test_book_ where test_book_.isbn='978'
select test_book0_.id as id1_0_0_, test_book0_.isbn as isbn2_0_0_, test_book0_.title as title3_0_0_ from Book test_book0_ where test_book0_.id=1

Session.byNaturalId loadOptional

package org.example.demo.hibernate;

import java.util.Optional;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.NaturalId;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;

public class Test {
    public static void main(String[] args) {
        ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .applySetting("hibernate.connection.url", "jdbc:p6spy:postgresql://localhost:5432/test")
                .applySetting("hibernate.connection.username", "postgres")
                .applySetting("hibernate.connection.password", "postgres")
                .applySetting("hibernate.hbm2ddl.auto", "create").build();
        Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClass(Book.class).getMetadataBuilder()
                .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();
        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
        Session session = sessionFactory.openSession();

        session.beginTransaction();
        Book book = new Book();
        book.title = "测试书";
        String isbn = "978";
        book.isbn = isbn;
        session.persist(book);
        session.getTransaction().commit();

        session.clear();

        Optional<Book> optionalBook = session.byNaturalId(Book.class).using("isbn", isbn).loadOptional();
        // class java.util.Optional
        System.out.println(optionalBook.getClass());
        // org.example.demo.hibernate.Test$Book@1b39fd82
        System.out.println(optionalBook.get());

        session.close();
        sessionFactory.close();
    }

    @Entity(name = "Book")
    public static class Book {
        @Id
        @GeneratedValue
        Integer id;
        String title;
        @NaturalId
        String isbn;
    }
}

生成的 SQL

drop table if exists Book cascade
drop sequence if exists hibernate_sequence

create sequence hibernate_sequence start 1 increment 1
create table Book (id int4 not null, isbn varchar(255), title varchar(255), primary key (id))
alter table Book add constraint UK_u31e1frmjp9mxf8k8tmp990i unique (isbn)
select nextval ('hibernate_sequence')
insert into Book (isbn, title, id) values ('978', '测试书', 1)

select test_book_.id as id1_0_ from Book test_book_ where test_book_.isbn='978'
select test_book0_.id as id1_0_0_, test_book0_.isbn as isbn2_0_0_, test_book0_.title as title3_0_0_ from Book test_book0_ where test_book0_.id=1

results matching ""

    No results matching ""