Spring/Hibernate/Oracle: ORA-02289 Sequence Does Not Exist? - java

Getting a java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist when trying to insert a new object into my Oracle table. The table does have a sequence that automatically increments upon each entry.
I've been stuck on this for a few hours and after following similar answers to this question and other articles, I'm still stuck.
My class:
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
#Entity
#Table(name = "MY_SCHEMA.MY_TABLE")
#Component
public class SomeClass {
#Id
#SequenceGenerator(name = "MY_SEQ", sequenceName = "MY_SEQ", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQ")
#Column(name = "MY_ID")
private Integer myId;
#Column(name = "MY_TS")
private Timestamp ts;
#Column(name = "MY_PARAM")
private String myParameters;
#Column(name = "ANOTHER_TS")
private Timestamp anotherTimestamp;
// empty constructor and getters/setters
}
DAO for the class:
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Component;
import mypackage.mysubpackage.SomeClass;
#Component
public class SomeClassDAO {
private Session currentSession;
private Transaction currentTransaction;
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(SomeClass.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
return factory;
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionWithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionWithTransaction() {
currentTransaction.commit();
currentSession.close();
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
// post
public void insertNew() {
SomeClass obj = new SomeClass();
obj.setParameters("abc");
getCurrentSession().save(obj);
}
}
DDL snippet for the sequence:
begin
if inserting then
if :NEW."MY_ID" is null then
select MY_SEQ.nextval into :NEW."MY_ID" from dual;
end if;
end if;
end;
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-5.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:oracle:thin:#servername.company.net:123:ABC</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.username">user</property>
<property name="connection.password">pass</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
mvc-dispatchet-servlet.xml snippet:
<context:component-scan base-package="mypackage.mysubpackage"></context:component-scan>
<mvc:annotation-driven/>
<context:annotation-config/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#servername.company.net:123:ABC"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="mypackage.mysubpackage"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManger"/>

begin
if inserting then
if :NEW."MY_ID" is null then
select MY_SEQ.nextval into :NEW."MY_ID" from dual;
end if;
end if;
end;
This looks to me like part of oracle trigger rather than actual oracle Sequence. Check if sequence is actually present with name "MY_SEQ" in your schema.
If you have the sequence in place with the current JPA annotations on your id column, you do not require the trigger. JPA itself can get the sequence next value without the trigger.
If you still want to continue using the trigger read here.

Related

hibernate MappingException:Unknown entity don't know why?

i have a problem and i need your help.i use eclipse 4.5.1. hibernate5.1
and here is the code
Exception in thread "main" org.hibernate.MappingException: Unknown entity: net.runze.hb1.entity.News
public class NewsManager {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration()
.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
Session sess = sf.openSession();
Transaction ta = sess.beginTransaction();
News n = new News();
n.setTitle("Aliens");
n.setContent("hahahaha!");
sess.save(n); // here is where it threw exception
ta.commit();
sess.close();
sf.close();
}
}
and i use annotation to the entity class:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="news_inf")
public class News {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String title;
private String content;
// getters and setters...
}
here is my 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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.aquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<mapping class="net.runze.hb1.entity.News" />
</session-factory>
</hibernate-configuration>
they says this problem will happen when my #Entity import the wrong package,or the hibernate.cfg.xml forgot the "mapping". both them i made it right but it still don't work.
It is simply :)
Configuration conf = new Configuration()
.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
Change to
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
you have to specify where your configuration file is:
onfiguration conf = new Configuration().configure("[your package]/hibernate.cfg.xml");

How To insert Gujarati in TextBox via Spring Hibernate in database?

I am trying to store gujarati in postgreSQL database using Java Spring Hibernate Project But it is storing something like this
મà«àª¦à«àª¨àª¾ àªàª¯-પરાàªàª¯ પાàªàª³ ઠવà«àª¯àªà«àª¤àª¿àª¨à«àª ભà«àªà«àª
instead of
મોદીના જય-પરાજય પાછળ આ વ્યક્તિનું ભેજું
In my database encoding is UTF-8, if I copy paste directly in postgreSQL it is storing properly but from html form in web application it is not storing properly.
Following is my hibernate.hbm.cfg file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
org.postgresql.Driver
</property>
<property name="connection.url">
jdbc:postgresql://192.168.6.51:5432/JayHind?autoReconnect=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=utf-8
</property>
<property name="connection.username">postgres</property>
<property name="connection.password">pshiv</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<mapping class="com.models.Role" />
<mapping class="com.models.UserAttempts" />
<mapping class="com.models.UserLogin" />
<mapping class="com.models.UserRole" />
<mapping class="com.models.Program" />
<mapping class="com.models.NationalProgram" />
<mapping class="com.models.StateProgram" />
<mapping class="com.models.OtherProgram" />
<mapping class="com.models.Video" />
<mapping class="com.models.Contact" />
<mapping class="com.models.Heading" />
</session-factory>
</hibernate-configuration>
I have also used
% # page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" % >
in jsp pages this make gujarati display properly but in form submission there is still problem.
In model class
package com.models;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import com.sun.istack.internal.NotNull;
#Entity
#Table(name = "tbl_heading_info", uniqueConstraints = {
#UniqueConstraint(columnNames = "id")})
public class Heading {
private int id;
#NotNull
#NotBlank
private String message;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "message", nullable = false)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
/*byte ptext[] = null;
try {
ptext = message.getBytes("ISO_8859_1");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String value = new String(ptext, "UTF-8");
this.message=value;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */
}
}
I have also put filter in web.xml
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
Expected Output
Current Output
I had to face this the last week, try this.
Use 'definitivo' has the textBox.getText() and convert to UTF-8
byte ptext[] = definitivo.getBytes("ISO_8859_1");
String value = new String(ptext, "UTF-8");

Hibernate - Mapping table to Entity class does not work: QuerySyntaxException: Class is not mapped

I checked the numerous threads about this but no solutions are working. According to those threads, the mapping should work.
Exception in thread "main"
org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not
mapped [from Product]
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
...
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="api.test.model.Product" />
</session-factory>
</hibernate-configuration>
Product.java:
package api.test.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="products")
public class Product implements Serializable{
...
}
Dao:
public List<Product> getProduct(Integer id) {
List<Product> products = (List<Product>) openCurrentSessionwithTransaction()
.createQuery("from Product").setMaxResults(100).list();
return products;
}
This does not throw error but no results possible:
.createQuery("from " + Product.class.getName()).setMaxResults(100).list();
I also tried mapping the class in persistence.xml, doesn't work either:
<persistence-unit name="transactions-optional">
<class>api.test.model.Product</class>
Full stacktrace as requested
Thanks in advance.

MappingException: Named query not known

Trying to learn Hibernate, i am trying to learn how to execute NamedQuries but evertime i am getting Exception in thread "main" org.hibernate.MappingException: Named query not known.Please help me out here
Error (only the message, not showing complete stack)
Exception in thread "main" org.hibernate.MappingException: Named query not known: hibernate_tut_emp.Employee.FindCountOfNames
at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1372)
at hibernate_tut_emp.MyOps.main(MyOps.java:20)
Employee.java
package hibernate_tut_emp;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
#Entity
#Table(name="Hib1")
#NamedQueries({
#NamedQuery(name="GetDetailsByName" , query="select * from hib1 h where h.name=:name"),
#NamedQuery(name="FindCountOfNames", query="select count(1) as cnt from hib1 h where h.name=:name")
})
public class Employee {
private int id;
private String name;
#Id
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String empName) {
this.name = empName;
}
}
MyOps.java
package hibernate_tut_emp;
import java.util.Scanner;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class MyOps {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a name : ");
String name = scnr.next();
SessionFactory ses = HibernateUtil.getSessionFactory();
Session session = ses.openSession();
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
query.setString("name", name);
int count = ((Integer)query.iterate().next()).intValue();
System.out.println("count : "+count);
}
}
employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_tut_emp.Employee" table="hib1">
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">mayank</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="hibernate_tut_emp.Employee" />
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I googled out everything possible but i think i am overlooking some basic stuff.Any indication in right direction is appreciated! :)
One thing i considered is that if i have defined in class file NamedQueries, i do not need to mention it in xml file.Please correct me if i am wrong!
There are several issues here:
Your named queries should use entities not tables. If you want native queries you should use NamedNativeQuery instead.
You don't need to supply the entity name when fetching the query.
Change this:
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
to:
Query query = session.getNamedQuery("FindCountOfNames");

How to obtain an entitymanager in Spring 3 like you do in Java EE 6

I have used Java EE 6 before and I have created a connection resource (pooled) on the server and then bound it to a JNDI name which I have referenced inside the jta-data-source element tag in the Persistence.xml file.
Now I use Spring 3 and I have a hard time understanding all the different beans that I need to set up and why need to do so. EJB 3 automatically wrap the methods in transactions. In Spring it seems like you need to configure a transaction manager, however I don't know. Need explanation.
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/myapp" expected-type="javax.sql.DataSource"/>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.myapp.app"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQL82Dialect
</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />
I understand the jndi lookup for the data source, however I don't understand the rest thourougly. I am not able to insert/persist objects with this configuration.
I need an explanation on how Spring 3 differs from Java EE 6 in this area, and how to do it the same way.
After thinking a little more on your original question, I'd like to add:
Spring doesn't automatically wrap every method with a Transaction. You have to tell Spring where you want your Transactional Boundaries to be. You do that with either XML config or by using the #Transactional annotation.
You should have a look at where you should declare transactions - here and here.
You should have a look at Spring's Transaction Management - here.
You should have a look at Transaction Config - here.
I am still of the opinion that your config is good and that the trouble you are having lies within the beans attempting to use your EntityManager. I renew my request for you to post that, as I'm certain I could get you going if I could see it.
I've looked at your configuration and I can't find anything wrong with it. As an example, I will provide (at the bottom) something I have in a working application right now.
I don't believe your problem is within your configuration, but in your usage of the configured beans. If you could provide code showing me (us) how you are interacting with your EntityManager, I could probably identify your issue(s).
I'll provide you with working examples of a Entity, Repository, and XML Config to try and help you locate your issue:
Spring Config (applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.company.app.dao" />
<context:component-scan base-package="com.company.app.service" />
<jee:jndi-lookup id="dataSource"
jndi-name="jdbc/Test" />
<bean id="jpaDialect"
class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="packagesToScan" value="com.company.app.model" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManager" />
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
</beans>
Model
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#Entity
public class User {
#Id
private String id = UUID.randomUUID().toString();
#Column
#Length(min = 3, max = 25)
private String name;
#OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true)
#JoinColumn(name = "userId", nullable = false)
private Set<Contact> contacts = new HashSet<Contact>();
public UUID getId() {
return UUID.fromString(id);
}
public void setId(UUID id) {
this.id = id.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Contact> getContacts() {
return contacts;
}
public void setContacts(Set<Contact> contacts) {
this.contacts = contacts;
}
public void addContact(Contact contact) {
this.contacts.add(contact);
}
public void removeContact(Contact contact) {
this.contacts.remove(contact);
}
}
Repository
import com.company.app.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#Repository
public class UserDao {
#PersistenceContext
private EntityManager em;
#Transactional(propagation = Propagation.REQUIRED)
public void createUser(User user) {
em.persist(user);
}
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public User readUserById(UUID id) {
CriteriaQuery<User> query = em.getCriteriaBuilder().createQuery(User.class);
query.where (em.getCriteriaBuilder().equal(query.from(User.class).get("id"),id.toString()));
return em.createQuery(query).getSingleResult();
}
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Set<User> readAll() {
CriteriaQuery<User> query = em.getCriteriaBuilder().createQuery(User.class);
query.from(User.class);
return new HashSet<User>(em.createQuery(query).getResultList());
}
#Transactional(propagation = Propagation.REQUIRED)
public User update(User user) {
return em.merge(user);
}
#Transactional(propagation = Propagation.REQUIRED)
public void delete(User user) {
em.remove(user);
}
}

Categories