0

It's my day 2 in Java Hibernate. I'm learning form this YouTube tutorial:

Hibernate Tutorial | Configuration File

I'm carefully following each and every step. My problem is that I'm able to push same record many times:

mysql> select * from Alien;
+------+-------+--------+
| aid  | aname | acolor |
+------+-------+--------+
|  101 | Navin | Green  |
|  101 | Navin | Green  |
|  101 | Navin | Green  |
|  101 | Navin | Green  |
|  101 | Navin | Green  |
|  101 | Navin | Green  |
|  101 | Navin | Green  |
+------+-------+--------+
7 rows in set (0.00 sec)

Here are my files.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.password">cosmonauts</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">
            update
        </property>
        <property name="show_sql=true"></property>
    </session-factory>
</hibernate-configuration>

Alien.java

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

@Entity
public class Alien {  // POJO
    
    @Id
    private int aid;
    private String aname;
    private String acolor;
    
    ... //getters and setters
}

App.java // Main class

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class App {

    public static void main(String[] args) {
        Alien telusko = new Alien();
        telusko.setAid(101);
        telusko.setAname("Navin");
        telusko.setAcolor("Green");
        
        Configuration configuration = new Configuration().configure().addAnnotatedClass(Alien.class);
        
        StandardServiceRegistry reg = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sf = configuration.buildSessionFactory(reg);
        
        Session session = sf.openSession();
        
        Transaction tx = session.beginTransaction();
        session.save(telusko);
        tx.commit();
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.student.sample</groupId>
  <artifactId>StudentSystem</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.5.6.Final</version>
    </dependency>
</dependencies>
</project>

Did I misunderstand something. Please correct my mistake.

On console I'm getting this:

Aug 19, 2021 10:43:44 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.6.Final
Aug 19, 2021 10:43:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Aug 19, 2021 10:43:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Aug 19, 2021 10:43:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/testdb]
Aug 19, 2021 10:43:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 19, 2021 10:43:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 19, 2021 10:43:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Aug 19, 2021 10:43:45 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 19, 2021 10:43:45 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@27e7c77f] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Aug 19, 2021 10:43:45 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

Please pitch in.

1 Answer 1

0

The correct hibernate property for Hibernate 5.5.6.Final is hibernate.hbm2ddl.auto. See Hibernate Documentation here. So, please try replacing in your hibernate.cfg.xml.

<property name="hbm2ddl.auto">update</property>

with

<property name="hibernate.hbm2ddl.auto">update</property>

It's the generated DDL script which should ensure that there are no duplicates. With the incorrect property in place, Hibernate won't be able to update DDL for you.

Update

I tried and the application is working as expected and is generating the primary key constraints. Below are the generated logs -

Hibernate: create table Alien (aid integer not null, acolor varchar(255), aname varchar(255), primary key (aid)) engine=MyISAM
Hibernate: insert into Alien (acolor, aname, aid) values (?, ?, ?)
Aug 21, 2021 4:36:13 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.6.Final
Aug 21, 2021 4:36:13 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Aug 21, 2021 4:36:13 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Aug 21, 2021 4:36:13 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/testdb]
Aug 21, 2021 4:36:13 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 21, 2021 4:36:13 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 21, 2021 4:36:13 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sat Aug 21 16:36:14 IST 2021 WARN: This connection is using TLSv1.1 which is now deprecated and will be removed in a future release of Connector/J.
Aug 21, 2021 4:36:14 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Aug 21, 2021 4:36:14 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@411a5965] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Aug 21, 2021 4:36:14 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

I changed these 3 lines in hibernate.cfg.xml file -

    <!-- used MySQL5Dialect in place of MySQLDialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- corrected the config. It must not be generating SQL statements because of it -->
    <property name="show_sql">true</property>

Notice that the generated logs has primary key (aid) now. If this constraint is present in your generated SQL, then it will start throwing ConstraintViolationException as you expect it to be.

Sign up to request clarification or add additional context in comments.

13 Comments

Nope. Didnt work. I can still see duplicate records. mysql> select * from Alien; +------+---------+--------+ | aid | aname | acolor | +------+---------+--------+ | 103 | Mridula | Red | | 103 | Mridula | Red | | 103 | Mridula | Red | +------+---------+--------+ 3 rows in set (0.00 sec)
@Tanzeel Can you try dropping the table and start all over again. I suspect schema can't be updated due to already duplicate records.
Dropped and recreated the table. Didnt work. Still I'm able to save same records again and again.
Is a skype call possible. I'll share the screen. My timezone is Bangalore, India
Can you update generated schema in your question ? Do you see primary key there ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.