Hibernate with H2 getting errors when establishing entity manager (Eclipse/Java) - java

below is the error I am receiving when I run the test class given to me for the assignment:
2019-11-14T19:58:38.309Z [34mINFO [0;39m [main ] [36mc.a.cst8277.assignment3.Test[0;39m - setup JPA EntityManagerFactory, create EntityManager (Session)
2019-11-14T19:58:40.004Z [34mINFO [0;39m [main ] [36meclipselink.logging.all[0;39m - EclipseLink, version: Eclipse Persistence Services - 2.7.3.v20180807-4be1041
2019-11-14T19:58:40.021Z [34mINFO [0;39m [main ] [36meclipselink.logging.connection[0;39m - connecting(DatabaseLogin(
platform=>H2Platform
user name=> "sa"
datasource URL=> "jdbc:h2:mem:Assignment3"
))
2019-11-14T19:58:40.429Z [34mINFO [0;39m [main ] [36meclipselink.logging.connection[0;39m - Connected: jdbc:h2:mem:Assignment3
User: SA
Database: H2 Version: 1.4.199 (2019-03-13)
Driver: H2 JDBC Driver Version: 1.4.199 (2019-03-13)
2019-11-14T19:58:40.512Z [1;31mERROR[0;39m [main ] [36meclipselink.logging.all[0;39m - Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-46] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: There should be one non-read-only mapping defined for the primary key field [PORTFOLIO.PORTFOLIO_ID].
Descriptor: RelationalDescriptor(com.algonquincollege.cst8277.assignment3.model.Portfolio --> [DatabaseTable(PORTFOLIO)])
The last portion repeats for all the classes and I also get another set of errors which also repeats for all the classes I have created:
Exception [EclipseLink-41] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A non-read-only mapping must be defined for the sequence number field.
Descriptor: RelationalDescriptor(com.algonquincollege.cst8277.assignment3.model.Portfolio --> [DatabaseTable(PORTFOLIO)])
Here is the test class I need to run:
/**************************************************************G*********o****o****g**o****og**joob*********************
* File: Test.java
* Course materials (19F) CST 8277
* #author Mike Norman
*
* #date 2019 10
*/
package com.algonquincollege.cst8277.assignment3;
import java.lang.invoke.MethodHandles;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.algonquincollege.cst8277.assignment3.dao.BankUserDAOImpl;
public class Test {
private static final Class<?> _thisClaz = MethodHandles.lookup().lookupClass();
private static final Logger logger = LoggerFactory.getLogger(_thisClaz);
public static final String ASSIGNMENT3_PU_NAME = "Assignment3-main-PU";
public static void main(String[] args) {
logger.info("setup JPA EntityManagerFactory, create EntityManager (Session)");
EntityManagerFactory emf = Persistence.createEntityManagerFactory(ASSIGNMENT3_PU_NAME);
EntityManager em = emf.createEntityManager();
em.close();
emf.close();
}
}
Here is one of the 8 classes in question, the error I posted specifically references this class/table but all others are setup similarly and have similar error messages:
package com.algonquincollege.cst8277.assignment3.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the PORTFOLIO database table.
*
*/
#Entity
#NamedQuery(name="Portfolio.findAll", query="SELECT p FROM Portfolio p")
public class Portfolio extends ModelBase implements Serializable {
private static final long serialVersionUID = 1L;
private List<Asset> assets;
public Portfolio() {
}
#Override
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PORTFOLIO_ID", insertable=false, updatable=false)
public int getId() {
return this.id;
}
//bi-directional many-to-one association to Asset
#OneToMany(mappedBy="portfolio")
public List<Asset> getAssets() {
return this.assets;
}
public void setAssets(List<Asset> assets) {
this.assets = assets;
}
public Asset addAsset(Asset asset) {
getAssets().add(asset);
asset.setPortfolio(this);
return asset;
}
public Asset removeAsset(Asset asset) {
getAssets().remove(asset);
asset.setPortfolio(null);
return asset;
}
}

Try changing insertable to true for id field. Like this:
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PORTFOLIO_ID", insertable=true, updatable=false)
public int getId() {
return this.id;
}

Related

Hibernate GenerationType.Table

When using Hibernate GenerationType.Table strategy, do we need to have a table already created in the database for key generation, or can Hibernate create one by itself if no data is provided?
I have searched it on the internet and couldn't find a satisfactory answer.
In my code, when using AUTO type,it selects Table strategy which throws an exception that has something to do with the absence of a table for key generation in MySQL db. Just needed to confirm if it is the expected behaviour.
ERROR
DEBUG - select tbl.next_val from hibernate_sequences tbl where tbl.sequence_name=? for update
ERROR - HHH000351: Could not read or init a hi value
java.sql.SQLSyntaxErrorException: Table 'ifinances.hibernate_sequences' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1005)
at org.hibernate.id.enhanced.TableGenerator.executeQuery(TableGenerator.java:705)
at org.hibernate.id.enhanced.TableGenerator.access$400(TableGenerator.java:132)
at org.hibernate.id.enhanced.TableGenerator$1$1.execute(TableGenerator.java:589)
at org.hibernate.id.enhanced.TableGenerator$1$1.execute(TableGenerator.java:575)
at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
at org.hibernate.id.enhanced.TableGenerator$1.getNextValue(TableGenerator.java:574)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.TableGenerator.generate(TableGenerator.java:570)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:119)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:176)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:712)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:704)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:699)
at com.infiniteskills.data.Application.main(Application.java:42)
ERROR - Table 'ifinances.hibernate_sequences' doesn't exist
Entity class
#Entity
#Table(name = "BANK")
public class Bank {
#Id
/*
* #GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
*
* #GenericGenerator(name = "native", strategy = "native")
*/
#GeneratedValue(strategy = GenerationType.TABLE)
#Column(name = "BANK_ID")
private Long bankId;
#Column(name = "NAME")
private String name;
#Embedded
private Address address = new Address();
application class
package com.infiniteskills.data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import org.hibernate.Session;import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import com.infiniteskills.data.entities.Bank;
import com.infiniteskills.data.entities.TimeTest;
import com.infiniteskills.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.getTransaction().begin();
/*
* TimeTest test = new TimeTest(new Date()); session.save(test);
* session.getTransaction().commit();
*
* session.refresh(test);
*
* System.out.println(test);
*/
Bank bank = new Bank();
bank.setName("State Bank");
bank.setAddressLine1("Ranibagh");
bank.setAddressLine2("Haldwani");
bank.setCity("Nainital");
bank.setState("UK");
bank.setZipCode("63139");
bank.setCreatedBy("Vaibhav Pandey");
bank.setLastUpdatedBy("Vaibhav Pandey");
bank.setCreatedDate(LocalDateTime.now());
bank.setLastUpdatedDate(LocalDateTime.now());
bank.setInternational(false);
session.save(bank);
session.getTransaction().commit();

Spring Boot JPA 2 databases

I am using hibernate, spring boot, jpa
First DB is MS SQL. New requirement is to connect Oracle JDBC
It is multi module application. In main module i have application-remote.yml file with DB credentials. Here it is
spring:
datasource:
driver-class-name:com.microsoft.sqlserver.jdbc.SQLServerDriver
url: ************
username: *****
password: *****
secondDatasource:
driver-class-name: oracle.jdbc.OracleDriver
url: ***********
username: ******
password: ******
jpa:
hibernate:
ddl-auto: none
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
properties:
dialect: org.hibernate.dialect.SQLServer2012Dialect
jackson:
date-format: com.fasterxml.jackson.databind.util.StdDateFormat
logging:
config: classpath:logback-remote.xml
file: /usr/share/tomcat/pqa.log
My Application config in module app, com.my.project
#Configuration
#Import({
ControllerConfig.class,
PersistenceConfig.class
})
public class ApplicationConfig {
}
My persistenceConfig in module persistence com.my.project
#Configuration
public class PersistenceConfig {
#Bean
#Primary
#ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix="spring.secondDatasource")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
I have many entities in persistence com.my.project.entity
One of them is
#Data
#Entity
#Builder
#Table(name = "locationSelection", schema = "dbo")
public class Location {
#Id
#Column(name = "timerName")
private String timerName;
#Column(name = "center")
private String center;
#Column(name = "station")
private String station;
#Column(name = "cell")
private String cell;
#Column(name = "place")
private String place;
}
Repository for it in Persistence, com.my.project.repository
#Repository
public interface LocationRepository extends JpaRepository<Location, String> {}
And for 2nd databe in Persistence com.my.project.entityForIntegration
#Data
#Builder
#Entity
#Table(name = "PQA_IN")
public class Pqa_In {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private int id;
#Column(name = "STATUS")
private String status;
#Column(name = "UPD_USER")
private String upd_user;
#Column(name = "UPD_DATE")
private Timestamp upd_date;
#Column(name = "INS_USER")
private String ins_user;
#Column(name = "INS_DATE")
private Timestamp ins_date;
}
And repository in com.my.project.repositoryForIntegration
public interface Pqa_In_repository extends JpaRepository<Pqa_In, Long> {
}
Now this is doesnt work. I have a lot of erros, with the classes and configs above the error is
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.my.project.services.impl.AnomaliesServiceImpl required a bean of type 'com.my.project.repository.AnomaliesRepository' that could not be found.
Action:
Consider defining a bean of type 'com.my.project.repository.AnomaliesRepository' in your configuration.
I have read Spring documentation, baeldung, stackoverflow and other sites with guides and questions about multiple datasources, but i cant do nothing.
Please, provide me the correct solution to connect 2 DBs.
AnomaliesServiceImpl
#Service
#Slf4j
public class AnomaliesServiceImpl implements AnomaliesService {
private AnomaliesRepository anomaliesRepository;
#Autowired
public AnomaliesServiceImpl(AnomaliesRepository anomaliesRepository) {
//
this.anomaliesRepository = anomaliesRepository;
}
#Override
public ResponseEntityDTO getAllAnomalies(int currentPageNumber, int pageSize) {
Page<WeldMeasureProt> page = anomaliesRepository.findAllAnomalies(pageable);
return convertToWeldMeasureProtDTO(page, currentPageNumber);
}
AnomaliesRepository
#Repository
public interface AnomaliesRepository extends PagingAndSortingRepository<WeldMeasureProt, WeldMeasurePointPrimaryKey> {
#Query("from WeldMeasureProt wm where wm.detection<>0 " +
"and wm.uirQStoppActCntValue=0 " +
"and wm.monitorState=0 ")
Page<WeldMeasureProt> findAllAnomalies(Pageable pageable);
}

Hibernate integrity constraint violation: NOT NULL check constraint: For onetoOne Mapping using spring boot crud

I am trying to create onetoone mapping between two tables where the parent key primary key acts as the primary key for child as well. While trying to save parent I am getting the following error.
Please find the below console log, model classes and service class used for the same. Can someone pls help to resolve the error.
Basically want to transfer the order id from order class to order id under compensation using crud repo.
Parent class:
package com.newModel;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="ORDERS")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDER_ID")
private String orderId;
#Column(name="ACCESS_ID")
private String accessId;
#OneToOne(cascade=CascadeType.ALL,mappedBy="order",fetch=FetchType.EAGER)
private Compensation compensation;
//getters & setters
}
Child Class:
package com.newModel;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="COMPENSATION")
#NamedQuery(name="Compensation.findAll", query="SELECT o FROM Compensation o")
public class Compensation implements Serializable {
private static final long serialVersionUID = 1L;
/*#Id
#Column(name="ORDER_ID")
private String orderId;*/
#Column(name="CHANNEL_DEALER_CODE")
private String channelDealerCode;
//bi-directional one-to-one association to Order
#Id
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="ORDER_ID")
private Order order;
}
Service class:
package com.sample.service;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.newModel.Order;
#Component
public class MobilityServiceImpl implements MobilityService {
#Autowired
private MobilityRepository mobilityRepo;
#Override
public Response getOrderDetails(String orderId) {
Order orderDetails=mobilityRepo.findByOrderId(orderId);
return Response.ok(orderDetails).build();
}
#Override
public Response saveOrderDetails(Order orderDetails) {
orderDetails.getCompensation().setOrder(orderDetails);
Order orderResponse =mobilityRepo.save(orderDetails);
String resp=orderResponse.getOrderId()+" is Success";
return Response.ok(resp).build();
}
}
Console log:
Hibernate: select order0_.order_id as order_id1_1_1_, order0_.access_id as access_i2_1_1_, compensati1_.order_id as order_id2_0_0_, compensati1_.channel_dealer_code as channel_1_0_0_ from orders order0_ left outer join compensation compensati1_ on order0_.order_id=compensati1_.order_id where order0_.order_id=?
Hibernate: select compensati0_.order_id as order_id2_0_0_, compensati0_.channel_dealer_code as channel_1_0_0_ from compensation compensati0_ where compensati0_.order_id=?
Hibernate: insert into orders (access_id, order_id) values (?, ?)
Hibernate: insert into compensation (channel_dealer_code, order_id) values (?, ?)
2018-11-23 16:13:53.210 WARN 17532 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: -10, SQLState: 23502
2018-11-23 16:13:53.211 ERROR 17532 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : integrity constraint violation: NOT NULL check constraint; SYS_CT_10118 table: COMPENSATION column: ORDER_ID
2018-11-23 16:13:53.214 ERROR 17532 --- [nio-8080-exec-1] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2018-11-23 16:13:53.244 ERROR 17532 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.hsqldb.HsqlException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10118 table: COMPENSATION column: ORDER_ID
JSON Request:
{
"orderId": "1006730",
"accessId": "1810_CRU",
"compensation": {
"channelDealerCode": "ABCD"
}
}
In yout Compensation entity you still need to have id and Order in separate properties and use MapsId to have the same id
#Entity
#Table(name="COMPENSATION")
#NamedQuery(name="Compensation.findAll", query="SELECT o FROM Compensation o")
public class Compensation implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String id;
#Column(name="CHANNEL_DEALER_CODE")
private String channelDealerCode;
#OneToOne(fetch = FetchType.LAZY)
#MapsId
private Order order;
}

Mapping error while persisting JPA object

I'm getting stuck with this error in a week. Could anyone explain why I'm getting this error and how to solve it?
I have an Entiry class Version and I want to return the Id after persist an Version entity object. But I'm getting this error:
Exception [EclipseLink-71] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while setting the value of the instance variable [id] to the value [38].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[id-->Version.ID]
Descriptor: RelationalDescriptor(varick.rap.demo.entities.VersionPK --> [DatabaseTable(Version)])
This is my full code:
factory = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
entity = factory.createEntityManager();
entity.getTransaction().begin();
Version version = new Version();
version.setVersion(getNext(this.version));
version.setProjectID(projectID);
entity.persist(version);
entity.flush();
System.out.println("Version Id: " + version.getId());
entity.getTransaction().commit();
Version entity class(this class is using an #EmbeddedId):
#Entity
#Table(name="Version")
public class Version implements Serializable {
#EmbeddedId
private VersionPK id;
#Column(name="Version")
private String version;
#Column(name="ProjectID")
private int projectID;
public Version() {
}
public VersionPK getId() {
return this.id;
}
//get and set methods here
VersionPK class:
#Embeddable
public class VersionPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
public VersionPK() {
}
//get and set method here
the primary key is not set. maybe you should do like this :
VersionPK pk = new VersionPK();
pk.setId("****");
Version version = new Version();
version.setId(pk);
version.setVersion(getNext(this.version));
version.setProjectID(projectID);
entity.persist(version);
entity.flush();
System.out.println("Version Id: " + version.getId());
entity.getTransaction().commit();

Persistance Unit Error More 2 EntityManagers 1 Persitance Unit?

Hi im working with Java EE 7. The code got the following structure.
model --> Entity Beans
business --> Service classes for the model (each contains a EntityManager)
presentation --> Named SessionScoped Beans with #EJB on the service
When i tested the program with just 1 service / EntityManager everything works fine but now when i added the second service class i got this error:
>
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [watchuwantPU] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class model.Tag] uses a non-entity [class java.lang.String] as target entity in the relationship attribute [field beschreibung].
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1950)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1941)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
persistence.xml
<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="watchuwantPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>watchuwant</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
FilmService.java
#Stateless
public class FilmService {
#PersistenceContext(name="watchuwantPU", unitName = "watchuwantPU")
private EntityManager em;
public void add(Film Film){
em.persist(Film);
}
public List<Film> findAll(){
return em.createQuery("select f from Film f order by f.id").getResultList();
}
}
LizenzPM.java
#SessionScoped
#Named
public class LizenzPM implements Serializable{
private String lizenzgeber;
private String lizenztyp;
private String lizenzurl;
private Date erteiltAm;
#EJB
private LizenzService service;
Film.java Entity
#Entity
public class Film implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String titel;
#OneToMany(mappedBy = "parent", cascade=CascadeType.ALL, orphanRemoval=true)
private List<Tag> tags = new LinkedList<>();
Tag.class Entity
#Entity
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(optional = false)
private String beschreibung;
private Film parent;
I think that the persistence unit name is watchuwantPU, not LizenzService. Check the #PersistenceContext annotation.

Categories

Resources