D
D
DmitryPros2018-03-21 22:55:06
PostgreSQL
DmitryPros, 2018-03-21 22:55:06

Java how to finally run Hibernate?

Hello everyone, I have already read a bunch of Hibernate 5 tutorials and some kind of boilerplate everywhere, I refuse to believe that in 2018 you need to create a bunch of .xml files to describe each Entity and the configuration of Hibernate itself. (Maybe there are some libraries for generating xml?)
I found this option (from the official docs):

Configuration cfg = new Configuration()
                .setProperty("hibernate.connection.driver_class", "org.postgresql.Driver")
                .setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/indicators_value")
                .setProperty("hibernate.connection.username", "postgres")
                ...
                .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL95Dialect")
                .setProperty("hibernate.connection.datasource", "java:com/driver/db/entity")
                .setProperty("hibernate.order_updates", "true")
                .addClass(MyClass.class);

Which, it seems, should replace a bunch of these xml files, but here's the problem:
org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : com/driver/db/entity/MyClass.hbm.xml

Those. it still requires those files.
I configure and make a request like this:
Session session = cfg.configure().buildSessionFactory().openSession();

        session.beginTransaction();
        String sql = "select version()";

        String result = (String) session.createNativeQuery(sql).getSingleResult();
        System.out.println(result);

        session.getTransaction().commit();
        session.close();

But the error crashes earlier, on the line. .addClass(MyClass.class);
The main question of this kind: How to configure Hibernate as simply as possible? And no matter what you need to create xml mappers with each new Entity
Toaster Wanderer, show me the way to the true manual, and may the force be with you!
And my gratitude :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Conacry, 2018-03-22
@DmitryPros

Hello.
First you need to have an annotated class associated with an entity in the database. Here is an example from my project:

@Entity
@Table(name = "users")
public class User implements Serializable {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
                    generator = "users_user_id_seq")
    @SequenceGenerator(name = "users_user_id_seq",
                       sequenceName = "users_user_id_seq",
                       allocationSize = 1)
    private long userId;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "login", nullable = false, unique = true)
    private String login;

    @Column(name = "password", nullable = false)
    private String password;

    @Column(name = "email", nullable = false, unique = true)
    private String email;

    @Column(name = "enabled", nullable = false)
    private boolean isEnabled;

    @Column(name = "reg_date", nullable = false)
    private Date regDate;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "authority_id", nullable = false)
    private Authority authority;

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isEnabled() {
        return isEnabled;
    }

    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    @JsonSerialize(using = SqlDateSerializer.class)
    public Date getRegDate() {
        return regDate;
    }

    public void setRegDate(Date regDate) {
        this.regDate = regDate;
    }

    public Authority getAuthority() {
        return authority;
    }

    public void setAuthority(Authority authority) {
        this.authority = authority;
    }

    @Override
    public String toString() {

        return  "User details" +
                "Id = " + getUserId() + "\n" +
                "Name = " + getName() + "\n" +
                "Login = " + getLogin() + "\n" +
                "Email = " + getEmail() + "\n" +
                "Enabled = " + isEnabled() + "\n" +
                "Role = " + getAuthority().getAuthority().name() + "\n" +
                "Registration date = " + getRegDate();
    }

If you do not understand any things from the entity class, write in a comment, I will answer.
Further, when configuring Hibernate, you need to specify not .addClass(MyClass.class), but configuration.addAnnotatedClass(Main.class).

S
Sergey Gornostaev, 2018-03-22
@sergey-gornostaev

Just use annotations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question