From a1bdae9e83d72203ec8bd23b7e4287f0d4f0adfc Mon Sep 17 00:00:00 2001 From: LeoMoulin Date: Wed, 20 Mar 2024 15:55:58 +0100 Subject: [PATCH] Add a prototype of RegNoGenerator wich needs further tests --- .../ovh/herisson/Clyde/RegNoGenerator.java | 35 +++++++++++++++++++ .../java/ovh/herisson/Clyde/Tables/User.java | 5 ++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 backend/src/main/java/ovh/herisson/Clyde/RegNoGenerator.java diff --git a/backend/src/main/java/ovh/herisson/Clyde/RegNoGenerator.java b/backend/src/main/java/ovh/herisson/Clyde/RegNoGenerator.java new file mode 100644 index 0000000..efa2047 --- /dev/null +++ b/backend/src/main/java/ovh/herisson/Clyde/RegNoGenerator.java @@ -0,0 +1,35 @@ +package ovh.herisson.Clyde; + +import org.hibernate.HibernateException; +import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.IdentifierGenerator; + +import java.io.Serializable; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +public class RegNoGenerator implements IdentifierGenerator { + @Override + public Object generate(SharedSessionContractImplementor session, Object object) { + try{ + JdbcConnectionAccess jdbccon = session.getJdbcConnectionAccess(); + Connection conn = jdbccon.obtainConnection(); + + Statement statement = conn.createStatement(); + String query = "select count(reg_no)+1 from Users"; + + ResultSet set = statement.executeQuery(query); + + if (set.next()){ + return set.getLong(1)+1000; + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + return null; + } +} diff --git a/backend/src/main/java/ovh/herisson/Clyde/Tables/User.java b/backend/src/main/java/ovh/herisson/Clyde/Tables/User.java index de958df..a42acbb 100644 --- a/backend/src/main/java/ovh/herisson/Clyde/Tables/User.java +++ b/backend/src/main/java/ovh/herisson/Clyde/Tables/User.java @@ -1,6 +1,8 @@ package ovh.herisson.Clyde.Tables; import jakarta.persistence.*; +import org.hibernate.annotations.GenericGenerator; + import java.util.Date; @@ -8,7 +10,8 @@ import java.util.Date; @Table(name = "Users") public class User { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GenericGenerator(name = "userGen", type = ovh.herisson.Clyde.RegNoGenerator.class) + @GeneratedValue(generator = "userGen") private Long regNo; private String lastName; private String firstName;