i have an issue when attempting to generate table with JBoss EAP 7.2.
My database is named KMT on MS SQL 2014, but when i run the JBoss EAP it creates the table in the system database named "master" despite I specified KMT in my connection-URL.
I created the datasource with the admin console of the JBoss EAP and when testing the connection i got a succes message.
My connection-URL:
JNDI Name: java:/MSSQLDS
Driver Name: sqljdbc42.jar
Connection URL: jdbc:microsoft:sqlserver://localhost:1433;databasename=KMT
My persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="KMT">
<jta-data-source>java:/MSSQLDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
And finally the entity I try to generate inside KMT database:
package be.Alstom.kmt.domaine;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#SuppressWarnings("serial")
#Entity
#Table(name="designer", schema="kmt")
public class Designer implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column
#NotNull
private String userName;
#Column
#NotNull
private String password;
public Designer() {
}
public Designer(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Designer other = (Designer) obj;
if (id != other.id)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
}
Here the my MSSQL server. Hibernate create table in systemdatabase/master instead of KMT.
Related
Hi i am trying to delect some entities from database, but when i use #Delete i get error in browsers, but Get is working. I am using hibernate JPA
Here are my code samples
#Entity
package pl.test.model;
import javax.persistence.*;
import java.util.Collection;
#Entity
public class Mestechnologygroup {
private Integer idTechnologyGroup;
private String name;
private String description;
private Integer number;
private Collection<Mestechnology> mestechnologiesByIdTechnologyGroup;
#Id
#Column(name = "idTechnologyGroup")
public Integer getIdTechnologyGroup() {
return idTechnologyGroup;
}
public void setIdTechnologyGroup(Integer idTechnologyGroup) {
this.idTechnologyGroup = idTechnologyGroup;
}
#Basic
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "Description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Basic
#Column(name = "Number")
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mestechnologygroup that = (Mestechnologygroup) o;
if (idTechnologyGroup != null ? !idTechnologyGroup.equals(that.idTechnologyGroup) : that.idTechnologyGroup != null)
return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (description != null ? !description.equals(that.description) : that.description != null) return false;
if (number != null ? !number.equals(that.number) : that.number != null) return false;
return true;
}
#Override
public int hashCode() {
int result = idTechnologyGroup != null ? idTechnologyGroup.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
#OneToMany(mappedBy = "mestechnologygroupByIdTechnologyGroup")
public Collection<Mestechnology> getMestechnologiesByIdTechnologyGroup() {
return mestechnologiesByIdTechnologyGroup;
}
public void setMestechnologiesByIdTechnologyGroup(Collection<Mestechnology> mestechnologiesByIdTechnologyGroup) {
this.mestechnologiesByIdTechnologyGroup = mestechnologiesByIdTechnologyGroup;
}
}
presistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="testPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>pl.test.model.Mesattachmentoperation</class>
<class>pl.test.model.Mesattachmenttechnology</class>
<class>pl.test.model.Mesoperation</class>
<class>pl.test.model.Mesoperationdictionary</class>
<class>pl.test.model.Mesoperationstate</class>
<class>pl.test.model.Mesproduct</class>
<class>pl.test.model.Mesproducttype</class>
<class>pl.test.model.Mesproductxoperation</class>
<class>pl.test.model.Mesresource</class>
<class>pl.test.model.Mesresourcexoperation</class>
<class>pl.test.model.Mestechnology</class>
<class>pl.test.model.Mestechnologygroup</class>
<class>pl.test.model.Mesusers</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/mes"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="xxxx"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
</properties>
</persistence-unit>
</persistence>
Repository with method
package pl.test.repo;
import com.sun.istack.internal.NotNull;
import pl.test.model.Mestechnologygroup;
import pl.test.model.Mesusers;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.List;
import static javax.transaction.Transactional.TxType.REQUIRED;
import static javax.transaction.Transactional.TxType.SUPPORTS;
#Transactional(SUPPORTS)
public class TechnologyGroupRepo {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testPU");
EntityManager em = entityManagerFactory.createEntityManager();
public Mestechnologygroup find(#NotNull Integer id) {
return em.find(Mestechnologygroup.class, id);
}
public List<Mestechnologygroup> findAll() {
TypedQuery<Mestechnologygroup> query = em.createQuery("from Mestechnologygroup ", Mestechnologygroup.class);
return query.getResultList();
}
#Transactional(REQUIRED)
public void delete(#NotNull Integer id) {
em.remove(em.getReference(Mestechnologygroup.class, id));
}
}
here i use #Delete
package pl.test.rest;
import pl.test.model.Mestechnologygroup;
import pl.test.repo.TechnologyGroupRepo;
import javax.inject.Inject;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
import static javax.transaction.Transactional.TxType.REQUIRED;
import static javax.transaction.Transactional.TxType.SUPPORTS;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
#Path("/tg")
public class TechnologyGroupEndpoint{
#Inject
private TechnologyGroupRepo technologyGroupRepo;
#GET
#Path("/{id : \\d+}")
#Produces(APPLICATION_JSON)
public Response getBook(#PathParam("id") #Min(1) Integer id) {
Mestechnologygroup mestechnologygroup = technologyGroupRepo.find(id);
if (mestechnologygroup == null)
return Response.status(Response.Status.NOT_FOUND).build();
return Response.ok(mestechnologygroup).build();
}
#DELETE
#Path("/d/{id : \\d+}")
public Response deleteBook(#PathParam("id") #Min(1) Integer id) {
technologyGroupRepo.delete(id);
return Response.noContent().build();
}
#GET
#Produces(APPLICATION_JSON)
public Response getBooks() {
List<Mestechnologygroup> mestechnologygroups = technologyGroupRepo.findAll();
if (mestechnologygroups.size() == 0)
return Response.status(Response.Status.NO_CONTENT).build();
return Response.ok(mestechnologygroups).build();
}
}
I revice that response in Google chrome
Response
I would appreciate any help :) Thanks in advance;)
The problem that you are facing is because a browser url is always accessed via GET http method. You cannot do for other http methods.
In order to test your DELETE endpoint, you have to do it using a REST client.
A few examples of rest clients: command line: curl, wget. With GUI: Postman, Insomnia.
An example of doing this from the command line:
curl -X DELETE "http://localhost:8080/test-1.0-SNAPSHOT/resources/tg/d/22"
#Delete i get error in browsers, but Get is working.
When you hit url on browser, it takes as GET request.
you can not make any other request than GET by browser, so GET works.
Try using http client tool like postman etc. or curl.
Is there a problem in my code ? I cannot retrieve the changes on my User entity without restarting the application.
Here is my persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pu" transaction-type="RESOURCE_LOCAL">
<properties>
<property name = "hibernate.show_sql" value = "true" />
</properties>
</persistence-unit>
</persistence>
I create my EntityManagerFactory this way:
public static EntityManagerFactory entityManagerFactory(String driver, String url, String user, String password, DataSource datasource) {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
DBPoolDataSource dataSource = new DBPoolDataSource();
dataSource.setName("pool-ds");
dataSource.setDescription("Pooling DataSource");
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setMinPool(5);
dataSource.setMaxPool(10);
dataSource.setMaxSize(30);
dataSource.setIdleTimeout(3600);
dataSource.setValidationQuery("SELECT id FROM test");
entityManagerFactory.setDataSource(datasource);
entityManagerFactory.setPersistenceUnitName("pu");
entityManagerFactory.setJpaDialect(new HibernateJpaDialect());
entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> props = entityManagerFactory.getJpaPropertyMap();
props.put("hibernate.cache.use_second_level_cache", "false");
props.put("hibernate.cache.use_query_cache", "false");
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
Here is my Entity:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "USER")
public class User {
#Id
private String trigram;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
public String getTrigram() {
return trigram;
}
public void setTrigram(String trigram) {
this.trigram = trigram;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (!trigram.equals(user.trigram)) return false;
if (firstName != null ? !firstName.equals(user.firstName) : user.firstName != null) return false;
return lastName != null ? lastName.equals(user.lastName) : user.lastName == null;
}
#Override
public int hashCode() {
int result = trigram.hashCode();
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
return result;
}
}
Here is my repository:
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
public class UserDao {
private EntityManager entityManager;
public UserDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
public User getByTrigram(String trigram) throws NoResultException {
entityManager.getEntityManagerFactory().getCache().evictAll();
TypedQuery<User> q = entityManager.createQuery(
"select u from User u where u.trigram = :trigram", User.class);
q.setParameter("trigram", trigram);
q.setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS);
return q.getSingleResult();
}
}
-> So the entity doesn't come from L1.
entityManagerFactory.getJpaPropertyMap() contains both:
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
-> So there should be no L2 nor from query cache.
But still, the changes made directly in my database are retrieved by my repository only after a restart.
Someone has an idea?
Thank you!
By default, Hibernate 4 has disabled L2 cache and query cache, so it's useless to configure hibernate.cache.use_second_level_cache=false and hibernate.cache.use_query_cache=fals.
The entity is cached in the hibernate Session (L1), and if you want to refresh this particular entity according to the underlying database, you can create a method like this:
public void refresh(User user) {
org.hibernate.Session session = entityManager.unwrap(Session.class);
session.refresh(user);
}
and call it after you retrieve the user, this way:
User currentUser = userDao.getByTrigram(login);
userDao.refresh(currentUser);
Hope it helped!
I'm new to hibernate and as I researched. When i want to start my JUnit, this mistake could be occur every time. I guess something wrong with my hbm.xml file. Maybe I am missing something because I'm still new to hibernate.
This is my hbm.xml file.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.UserEntity" table="user" schema="" catalog="junwa">
<id name="id" column="id"/>
<property name="username" column="username"/>
<property name="gender" column="gender"/>
<property name="birthday" column="birthday"/>
<property name="addres" column="addres"/>
</class>
</hibernate-mapping>
And this is my UserEntity.java file
package com.test;
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "user", schema = "", catalog = "junwa")
public class UserEntity {
private int id;
private String username;
private String gender;
private Timestamp birthday;
private String addres;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "gender")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Basic
#Column(name = "birthday")
public Timestamp getBirthday() {
return birthday;
}
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
#Basic
#Column(name = "addres")
public String getAddres() {
return addres;
}
public void setAddres(String addres) {
this.addres = addres;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
if (id != that.id) return false;
if (username != null ? !username.equals(that.username) : that.username != null) return false;
if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;
if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
if (addres != null ? !addres.equals(that.addres) : that.addres != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (gender != null ? gender.hashCode() : 0);
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
result = 31 * result + (addres != null ? addres.hashCode() : 0);
return result;
}
}
This is my test file.
/**
* Created by junwa on 2017/4/2.
*/
import com.test.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
public class StudentsTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
#Before
public void init(){
// create a deploy object
Configuration config = new Configuration().configure();
// create a service licenced object
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
// create a session factory object
sessionFactory = config.buildSessionFactory(serviceRegistry);
// create a sessoin object
session = sessionFactory.openSession();
// start transaction
transaction = session.beginTransaction();
}
#After
public void destroy(){
// commit transaction
transaction.commit();
// close session
session.close();
// close session factory
sessionFactory.close();
}
#Test
public void testSaveStudents(){
// create a object
Students s = new Students(1,"junwa","male",new Date(),"Anhui");
// save object to mysql database
session.save(s);
session.flush();
}
}
This my output
enter image description here
As Faraz Durrani said when you already have done the mapping in hbm.xml file, why do you need annotations for? Or the vice versa.You have to remove one of them. I would say remove hbm.xml file and use Annotations only.
One more thing I have noticed that you are not closing the transection also.
You can't use hbm.xml and annotation at the same time.
How can I save collection of value type in hibernate with annotations - List of String List<String> or for example:
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private Set<History> history;
}
and here is value type:
public class History {
private String someAttribute;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((entry == null) ? 0 : entry.hashCode());
result = prime * result + ((entryDate == null) ? 0 : entryDate.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
History other = (History) obj;
if (entry == null) {
if (other.entry != null)
return false;
} else if (!entry.equals(other.entry))
return false;
if (entryDate == null) {
if (other.entryDate != null)
return false;
} else if (!entryDate.equals(other.entryDate))
return false;
return true;
}
}
Can anyone give some example with hibernate annotations?
For an entity to have collection value type, we need to create a separate table to hold this collection as single row of the entity will have multiple values of for this collection. Use #ElementCollection and #CollectionTable annotations on the collection value attribute.
#ElementCollection
#CollectionTable(name = "STUDENT_HISTORY", joinColumns = {#JoinColumn(name = STUDENT_ID) })
#Column(name="HISTORY")
private Set<History> history;
The table will hold the collection values in the column HISTORY and uses STUDENT_ID column as the join column which will be the foreign key to the ID of student.
Below is a complete example using native Hibernate (I mean without the JPA):
Student.java
package domain.app.data;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
#Entity
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#ElementCollection
#CollectionTable(name="STUDENT_HISTORY", joinColumns={#JoinColumn(name="STUDENT_ID", referencedColumnName="ID")})
#Column(name="HISTORY")
private Set<History> history = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<History> getHistory() {
return history;
}
public void setHistory(Set<History> history) {
this.history = history;
}
#Override
public String toString() {
return "Student [id=" + id + ", history=" + history + "]";
}
}
History.java
package domain.app.data;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class History {
#Column(name="HISTORY")
private String someAttribute;
public String getSomeAttribute() {
return someAttribute;
}
public void setSomeAttribute(String someAttribute) {
this.someAttribute = someAttribute;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((someAttribute == null) ? 0 : someAttribute.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
History other = (History) obj;
if (someAttribute == null) {
if (other.someAttribute != null)
return false;
} else if (!someAttribute.equals(other.someAttribute))
return false;
return true;
}
}
HibernateUtil.java
package domain.app.data.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import domain.app.data.Student;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build();
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Student.class);
return configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSession() {
return sessionFactory;
}
}
Application.java
package domain.app;
import org.hibernate.Session;
import domain.app.data.History;
import domain.app.data.Student;
import domain.app.data.util.HibernateUtil;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSession().openSession();
session.getTransaction().begin();
Student student = new Student();
History history1 = new History();
history1.setSomeAttribute("Volunteer since 2016");
History history2 = new History();
history2.setSomeAttribute("Football team member");
student.getHistory().add(history1);
student.getHistory().add(history2);
session.save(student);
session.getTransaction().commit();
session.close();
}
}
hibernate.properties
hibernate.connection.username=admin
hibernate.connection.password=password
hibernate.connection.url=jdbc:h2:~/h2db/test
hibernate.connection.driver_class=org.h2.Driver
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration debug="false" scan="true" scanPeriod="30 minutes">
<appender name="Console-Appender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%gray(%d{yyyy-MM-dd HH:mm:ss.SSS}) %highlight(%5p) %gray(---) %magenta([%15.15t]) %cyan(%-40.40c{1}) %black(:) %m%n%xEx</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="Console-Appender" />
</root>
</configuration>
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackoverflow</groupId>
<artifactId>SO-41248001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
</project>
Project Structure:
Result in DB:
try this it should work.
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#ElementCollection
private Collection Set<History> history;
}
#Embeddable
public class History {
private String someAttribute;
......
}
i've this problem with my Enterprise Java Bean.
Log file:
stack trace
I don't know how to resolve it! This is my Entity class:
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author gfucc
*/
#Entity
#NamedQueries({
#NamedQuery(name = "Student.findAll", query = "SELECT s FROM Students"),
#NamedQuery(name = "Student.findByMatr", query = "SELECT s FROM Student s WHERE s.matricola = :matricola"),
#NamedQuery(name = "Student.findByCognome", query = "SELECT s FROM Student s WHERE s.cognome = :cognome")
})
public class Student
{
#Id #GeneratedValue
private String matricola;
#NotNull
#Column(length = 100)
private String nome;
#NotNull
#Column(length = 100)
private String cognome;
#NotNull
#Column(length = 100)
private String corsoLaurea;
#NotNull
#Size(min = 0, max = 30)
private int numEsamiSostenuti;
public Student()
{
}
public Student(String nome, String cognome, String corsoLaurea, int numEsamiSostenuti) {
this.nome = nome;
this.cognome = cognome;
this.corsoLaurea = corsoLaurea;
this.numEsamiSostenuti = numEsamiSostenuti;
}
public String getMatricola() {
return matricola;
}
public void setMatricola(String matricola) {
this.matricola = matricola;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getCorsoLaurea() {
return corsoLaurea;
}
public void setCorsoLaurea(String corsoLaurea) {
this.corsoLaurea = corsoLaurea;
}
public int getNumEsamiSostenuti() {
return numEsamiSostenuti;
}
public void setNumEsamiSostenuti(int numEsamiSostenuti) {
this.numEsamiSostenuti = numEsamiSostenuti;
}
#Override
public String toString() {
return "Student{" +
"matricola=" + matricola +
", nome=" + nome +
", cognome=" + cognome +
", corsoLaurea=" + corsoLaurea +
", numEsamiSostenuti=" + numEsamiSostenuti + '}';
}
}
This is my EJB:
package ejbs;
import entities.Student;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import qualifiers.Loggable;
/**
*
* #author gfucc
*/
#Stateless
#Loggable
public class StudentEJB implements StudentEJBRemote
{
#PersistenceContext(unitName = "StudentEJBPU")
private EntityManager em;
#Override
public Student createStudent(Student student)
{
em.persist(student);
return this.getStudentByMatricola(student.getMatricola());
}
#Override
public Student removeStudent(Student student)
{
Student toReturn = this.getStudentByMatricola(student.getMatricola());
if(toReturn != null)
{
em.remove(student);
return toReturn;
}
return null;
}
#Override
public Student updateStudent(Student student)
{
return em.merge(student);
}
#Override
public List<Student> getStudentList()
{
TypedQuery<Student> query = em.createNamedQuery("Student.findAll", Student.class);
return query.getResultList();
}
#Override
public Student getStudentByMatricola(String matricola)
{
TypedQuery<Student> query = em.createNamedQuery("Student.findByMatr", Student.class);
query.setParameter(1, matricola);
return query.getSingleResult();
}
#Override
public Student getStudentByCognome(String cognome)
{
TypedQuery<Student> query = em.createNamedQuery("Student.findByCognome", Student.class);
query.setParameter(1, cognome);
return query.getSingleResult();
}
}
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="StudentEJBPU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<class>entities.Student</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
This is my beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
Now in these images you can see my project structure:
project structure
What is the problem? I've all. The database i connected, i used a default database "sample"... The problem is on the persistence unit because without it i can build and then deploy without problem! Please help. Thanks a lot