Cannot persist record with a Persistent InputStream in OpenJPA - inputstream

I'm trying to persist a record that has a mapped #Persistent InputStream field.
the context is: JDK 1.8, LiferayPortal on Tomee 1.7.1 (OpenJPA 2.4-patch). Sorry about the stacktrace polluted by the Liferay one.
#Entity
#Table(name = "file_entries")
public class FileEntry implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(length = 120)
private String createdBy;
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Column(length = 120)
private String modifiedBy;
#Temporal(TemporalType.TIMESTAMP)
private Date modified;
#Column(length = 200)
private String title;
#Column(length = 2000)
private String description;
#Column(length = 240)
private String filename;
#Column(length = 60)
private String extension;
#Column(length = 20)
private String version;
#Column(length = 240)
private String contentType;
#Persistent(fetch = FetchType.LAZY)
private InputStream content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public InputStream getContent() {
return content;
}
public void setContent(InputStream content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
And when persisting:
logo = new FileEntry();
logo.setContent(new FileInputStream("some_local_file"));
entityService.persist(logo);
I get the following exception.
<openjpa-2.4.0-nonfinal-1598334-r422266:1599166 fatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction has been rolled back. See the nested exceptions for details on the errors that occurred.
at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2370)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2207)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2105)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1876)
at org.apache.openjpa.kernel.DelegatingBroker.flush(DelegatingBroker.java:1045)
at org.apache.openjpa.persistence.EntityManagerImpl.flush(EntityManagerImpl.java:663)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.zeroturnaround.jrebel.integration.openjpa.EntityManagerFactoryWrapper$ReloadingMethodHandler.invoke(EntityManagerFactoryWrapper.java:135)
at com.sun.proxy.$Proxy619.flush(Unknown Source)
at org.apache.openejb.persistence.JtaEntityManager.flush(JtaEntityManager.java:202)
at com.computas.generic.service.SimpleEntityService.persist(SimpleEntityService.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
at sun.reflect.GeneratedMethodAccessor585.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:227)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:194)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:308)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:303)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:308)
... 171 more
Caused by: <openjpa-2.4.0-nonfinal-1598334-r422266:1599166 fatal general error> org.apache.openjpa.persistence.PersistenceException: can't call setAutoCommit when the connection is JtaManaged
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4998)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4958)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:134)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:108)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:60)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:185)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:96)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:77)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:732)
at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:131)
... 204 more
Caused by: java.sql.SQLException: can't call setAutoCommit when the connection is JtaManaged
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.forbiddenCall(ManagedConnection.java:185)
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.invokeUnderTransaction(ManagedConnection.java:162)
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.invoke(ManagedConnection.java:93)
at com.sun.proxy.$Proxy618.setAutoCommit(Unknown Source)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.ConfiguringConnectionDecorator$ConfiguringConnection.setAutoCommit(ConfiguringConnectionDecorator.java:117)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.jdbc.sql.PostgresDictionary.insertPostgresBlob(PostgresDictionary.java:627)
at org.apache.openjpa.jdbc.sql.PostgresDictionary.insertBlobForStreamingLoad(PostgresDictionary.java:614)
at org.apache.openjpa.jdbc.meta.strats.LobFieldStrategy.insert(LobFieldStrategy.java:100)
at org.apache.openjpa.jdbc.meta.FieldMapping.insert(FieldMapping.java:623)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.insert(AbstractUpdateManager.java:238)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:165)
... 208 more
The persistence unit declaration is:
<persistence-unit name="uefiscdi" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>uefiscdiDS</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<property name="openjpa.jdbc.DBDictionary" value="postgres" />
<property name="openjpa.Log" value="DefaultLevel=INFO, Tool=INFO" />
</properties>
</persistence-unit>
The Datasource declaration is:
<Resource id="uefiscdiDS" type="DataSource">
JdbcDriver org.postgresql.Driver
JdbcUrl jdbc:postgresql://localhost:5432/db_name
UserName user_name
Password user_password
JtaManaged true
DefaultAutoCommit false
</Resource>
I tried with DefaultAutoCommit true / false / not declared ... same exception.

Just a shot in the dark, but have you tried calling em.persist(...) rather than em.merge(..)?
If that doesn't work it might be helpful if you posted the full stack trace somewhere. I'm afraid you might have snipped off the important parts.

Related

Android app crashes when I create instance for a java class

I was doing the update operation in Firebasae and im getting this error
here's the code
List<Student> studentsList;
mylistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,final int i, long id) {
Student students = studentsList.get(i);
showupdatedialogue(students.getName(),students.getName() );
return false;
}
});
Student students = studentsList.get(i); //line
App crashes on this line, "Student" is a java class
Student.java
package com.example.login;
import org.jetbrains.annotations.NotNull;
public class Student {
String name;
String roll_no;
String date_of_birth;
String class_section;
String class_teacher;
public Student(String name, String roll_no, String date_of_birth, String class_section, String class_teacher) {
this.name = name;
this.roll_no = roll_no;
this.date_of_birth = date_of_birth;
this.class_section = class_section;
this.class_teacher = class_teacher;
}
public String getName() {
return name;
}
public String getroll_no() {
return roll_no;
}
public String getdate_of_birth() {
return date_of_birth;
}
public String getclass_section() {
return class_section;
}
public String getclass_teacher() {
return class_teacher;
}
}
and I get this error, this says the size of the list is 0 but I have items in the list
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 18486
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.login.MainActivity$5.onItemLongClick(MainActivity.java:111)
at android.widget.AbsListView.performLongPress(AbsListView.java:3291)
at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:3206)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 18486 SIG: 9

Firebase snapshot getValue could not pars int suddenly

I hade a strange happening today with my Firebase project.
Suddenly the
AddressChatMessage chatMessage = snapshot.getValue(AddressChatMessage.class);
parsed everything ok for the AddressChatMessage except for one int.
Took me 2 hour until i tried this, setting the field to public
public int type;
Note I use this code for weeks without problem and today Android studio made some core updated to 2.3.2 and maybe that trigger this strange event.
Here´s the AddressChatMessage.java nothing strange except that the public int type cannot be private, if it is, it will be zero, that too is strange, usually Firebase give out a logcat warning when pojo parsing fails. I have 10 other modell classes like this with plenty of int´s
#IgnoreExtraProperties
public class AddressChatMessage {
// [START Firebase keys inside AddressChatMessage ]
#Exclude
public static final String TYPE = "type";
#Exclude
public static final String SENDER_ID = "senderId";
#Exclude
public static final String MESSAGE = "message";
#Exclude
public static final String FILENAME = "fileName";
#Exclude
public static final String DOWNLOAD_URI = "downloadUri";
#Exclude
public static final String TIME = "time";
// [STOP Firebase keys inside AddressChatMessage ]
public int type;
private String senderId;
private String message;
private String fileName;
private String downloadUri;
#Exclude
private long time;
#Exclude
private String messageId;
public AddressChatMessage() {
}
public AddressChatMessage(int type, String senderUid) {
this.senderId = senderUid;
this.type = type;
}
public AddressChatMessage(int type, String senderUid, String message) {
this.type = type;
this.senderId = senderUid;
this.message = message;
}
private int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDownloadUri() {
return downloadUri;
}
public void setDownloadUri(String downloadUri) {
this.downloadUri = downloadUri;
}
public long getTime() {
return time;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put(TYPE, type);
result.put(SENDER_ID, senderId);
result.put(MESSAGE, message);
result.put(FILENAME, fileName);
result.put(DOWNLOAD_URI, downloadUri);
result.put(TIME, time);
return result;
}
#Exclude
public boolean isTypeNormal() {
return getType() == ChatAdapter.MessageType.NORMAL.ordinal();
}
#Exclude
public boolean isTypeImage() {
return getType() == ChatAdapter.MessageType.IMAGE.ordinal();
}
}
When cleaning the code using Lint. Lint suggested changes like "This can be private instead of public" - I accidentally set the getType() to private access.

Form Gives 400 Bad Request error when using with Spring's ModelAttribute

i have html form which i forward to spring controller. Its works fine if i use getParameter but using modelAttribute it says 400 bad request error.
Here is my controller Code
#Controller
public class BookController {
#RequestMapping (value="/addBook")
public String addBook(#ModelAttribute Book book){
System.out.println(book.getBookName());
bookService.addBooks(book);
return "index";
}
}
This is Book model Code
#Entity
#Table (name = "Book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID",columnDefinition = "BIGINT NOT NULL AUTO_INCREMENT")
private long bookId;
#Column(name="book_code",columnDefinition = "VARCHAR(200) NOT NULL")
private String bookCode;
private String bookName;
private String author;
#Temporal (TemporalType.DATE)
private Date dateOfArrival;
private Double price;
private String rackNo;
private int numberOfBook;
private String subjectCode;
public Book() {
super();
}
public Book(String bookCode, String bookName, String author,
Date dateOfArrival, Double price, String rackNo,
int numberOfBook, String subjectCode) {
super();
this.bookCode = bookCode;
this.bookName = bookName;
this.author = author;
this.dateOfArrival = dateOfArrival;
this.price = price;
this.rackNo = rackNo;
this.numberOfBook = numberOfBook;
this.subjectCode = subjectCode;
}
public String getBookCode() {
return bookCode;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDateOfArrival() {
return dateOfArrival;
}
public void setDateOfArrival(Date dateOfArrival) {
this.dateOfArrival = dateOfArrival;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRackNo() {
return rackNo;
}
public void setRackNo(String rackNo) {
this.rackNo = rackNo;
}
public int getNumberOfBook() {
return numberOfBook;
}
public void setNumberOfBook(int numberOfBook) {
this.numberOfBook = numberOfBook;
}
public String getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(String subjectCode) {
this.subjectCode = subjectCode;
}
}
I have doubt that the problem is due to using date
Please Help me out
I would try 2 things.
In your Model add this:
//here use the same pattern of date your send from the view
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dateOfArrival;
In your controller
#RequestMapping (value="/addBook")
public String addBook(#ModelAttribute Book book, BindingResult result){
...
Then you will be able to debug your method and know the problem.

Adding spring-boot-starter-web to dependencies breaks multiple datasources

I have a project with 3 different DataSources. It works fine if the project is run from with spring-boot:run only with these dependencies:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>RELEASE</version>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-web</artifactId>-->
<!--</dependency>-->
Here is one datasource, they are all pretty much the same, just changing bean names and database information
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "emfIntranet", transactionManagerRef = "tmIntranet", basePackages = {"com.vnt.intranet.repositories"})
#ConfigurationProperties(prefix = "databases.sistemas")
public class IntranetPersistence {
private String address;
private String schema;
private String username;
private String password;
private String eclipselinklog;
private Boolean sqllog;
#Primary
#Bean(name = "dsIntranet")
public DataSource dataSource() {
org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setUrl("jdbc:postgresql://" + address + "/" + schema);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setInitialSize(3);
dataSource.setMaxIdle(10);
dataSource.setMaxActive(10);
return dataSource;
}
private EclipseLinkJpaVendorAdapter getEclipseLinkJpaVendorAdapter() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.PostgreSQLPlatform");
vendorAdapter.setShowSql(sqllog);
return vendorAdapter;
}
#Primary
#Bean(name = "emfIntranet")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(getEclipseLinkJpaVendorAdapter());
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("com.vnt.intranet.entities");
factoryBean.setPersistenceUnitName("intranet");
Properties jpaProperties = new Properties();
jpaProperties.put("eclipselink.weaving", "false");
jpaProperties.put("eclipselink.logging.level", eclipselinklog); // SEVERE / FINEST
factoryBean.setJpaProperties(jpaProperties);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
#Primary
#Bean(name = "tmIntranet")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
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;
}
public String getEclipselinklog() {
return eclipselinklog;
}
public void setEclipselinklog(String eclipselinklog) {
this.eclipselinklog = eclipselinklog;
}
public Boolean getSqllog() {
return sqllog;
}
public void setSqllog(Boolean sqllog) {
this.sqllog = sqllog;
}
}
I can access all datasources with no problem... One of them is annotated with #Primary.
But if I uncomment spring-boot-starter-web dependency it breaks it and gives me:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: more than one 'primary' bean found among candidates: [emfIntranet, entityManagerFactory, emfMkRadius, emfMkData]
I'm trying to convert this to a web project with no success...
Any ideas?
EDIT
Adding other classes for clarity:
MkDataPersistence.class
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "emfMkData", transactionManagerRef = "tmMkData", basePackages = {"org.example.mkdata.repositories"})
#ConfigurationProperties(prefix = "databases.mkdata")
public class MkDataPersistence {
private String address;
private String schema;
private String username;
private String password;
private String eclipselinklog;
private Boolean sqllog;
#Bean(name = "dsMkData")
javax.sql.DataSource dataSource() {
DataSource dataSource = new DataSource();
dataSource.setUrl("jdbc:postgresql://" + address + "/" + schema);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setInitialSize(3);
dataSource.setMaxIdle(10);
dataSource.setMaxActive(10);
return dataSource;
}
#Bean
HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQL9Dialect");
vendorAdapter.setShowSql(sqllog);
return vendorAdapter;
}
#Bean(name = "emfMkData")
EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("org.example.mkdata.entities");
factoryBean.setPersistenceUnitName("mkdata");
Properties jpaProperties = new Properties();
jpaProperties.put("eclipselink.weaving", "false");
jpaProperties.put("eclipselink.logging.level", eclipselinklog); // SEVERE / FINEST
factoryBean.setJpaProperties(jpaProperties);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
#Bean(name = "tmMkData")
PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
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;
}
public String getEclipselinklog() {
return eclipselinklog;
}
public void setEclipselinklog(String eclipselinklog) {
this.eclipselinklog = eclipselinklog;
}
public Boolean getSqllog() {
return sqllog;
}
public void setSqllog(Boolean sqllog) {
this.sqllog = sqllog;
}
}
MkRadiusPersistence.class
#Configuration
#EnableTransactionManagement()
#EnableJpaRepositories(entityManagerFactoryRef = "emfMkRadius", transactionManagerRef = "tmMkRadius", basePackages = {"org.example.mkradius.repositories"})
#ConfigurationProperties(prefix = "databases.mkradius")
public class MkRadiusPersistence {
private String address;
private String schema;
private String username;
private String password;
private String eclipselinklog;
private Boolean sqllog;
#Bean(name = "dsMkRadius")
javax.sql.DataSource dataSource() {
DataSource dataSource = new DataSource();
dataSource.setUrl("jdbc:postgresql://" + address + "/" + schema);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setInitialSize(3);
dataSource.setMaxIdle(10);
dataSource.setMaxActive(10);
return dataSource;
}
#Bean
HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQL9Dialect");
vendorAdapter.setShowSql(sqllog);
return vendorAdapter;
}
#Bean(name = "emfMkRadius")
EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("org.example.mkradius.entities");
factoryBean.setPersistenceUnitName("mkradius");
Properties jpaProperties = new Properties();
jpaProperties.put("eclipselink.weaving", "false");
jpaProperties.put("eclipselink.logging.level", eclipselinklog); // SEVERE / FINEST
factoryBean.setJpaProperties(jpaProperties);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
#Bean(name = "tmMkRadius")
PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
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;
}
public String getEclipselinklog() {
return eclipselinklog;
}
public void setEclipselinklog(String eclipselinklog) {
this.eclipselinklog = eclipselinklog;
}
public Boolean getSqllog() {
return sqllog;
}
public void setSqllog(Boolean sqllog) {
this.sqllog = sqllog;
}
}
EDIT 2
Application.class
#Configuration
#ComponentScan(basePackages = { "org.example.startup" })
#EnableAutoConfiguration
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
#Autowired
CableRouteRepository cableRouteRepository;
#Autowired
CityRepository cityRepository;
#Autowired
RadAcctRepository radAcctRepository;
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.showBanner(false)
.sources(Application.class)
.run(args);
Application app = context.getBean(Application.class);
// for (String bean: context.getBeanDefinitionNames()) {
// logger.info(bean);
// }
app.start();
}
private void start() {
logger.info("Application.start()");
logger.info("{}", cableRouteRepository.findAll());
logger.info("{}", cityRepository.findAll());
logger.info("{}", radAcctRepository.findTest());
}
}
This is the starter class... I printed every repository as a test (each repository here is on a different DataSource)... They work fine as long as I don't have spring-starter-web on the classpath.
EDIT 3
Github Repo
https://github.com/mtrojahn/test-multiple-databases
I hope I did it right... I never really worked with Github :)
EDIT 4
Github updated properly with the failing code.
As a reminder if the dependency bellow is commented, the code works:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
And if the dependency above is uncommented but the code bellow is changed in the IntranetPersistence.class from:
#Primary
#Bean(name = "emfIntranet")
to
#Primary
#Bean(name = "entityManagerFactory")
It overwrites the default bean and starts to fail with:
Caused by: java.lang.IllegalArgumentException: Not an managed type: class org.example.intranet.entities.CableRoute
You're being affected by the behaviour of Spring Boot 1.2's JPA auto-configuration. It only switches off the creation of its own entityManagerFactory bean if there's a user-defined LocalContainerEntityManagerFactoryBean. You're using LocalContainerEntityManagerFactoryBean but calling afterPropertiesSet and getObject on it yourself rather than allowing the container to do so for you. This leaves the context will multiple #Primary EntityManagerFactory beans. This has been improved in Spring Boot 1.3 so that a user-declared EntityManagerFactory bean will also switch off the auto-configuration.
This causes a problem when trying to create openEntityManagerInViewInterceptor as it needs an EntityManagerFactory and the context has no way of knowing whic of the two #Primary beans it should choose.
There are a few ways to proceed. You could update your configuration to define beans that are of type LocalContainerEntityManagerFactoryBeans rather than EntityManagerFactory. Another is to disable the creation of the interceptor by adding the following to your application.yml:
spring:
jpa:
open_in_view: false

Having an exception when using TopLink on WebLogic

I get the below exception when trying to run an EJB application using TopLink on WebLogic application server.
java.lang.IllegalArgumentException: NamedQuery of name: TblPkgFeature.getFeaturesData not found:
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getDatabaseQuery(EJBQueryImpl.java:422)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:657)
at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.setParameter(EJBQueryImpl.java:202)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weblogic.persistence.InterceptingInvocationHandlerImpl.invoke(InterceptingInvocationHandlerImpl.java:29)
at $Proxy110.setParameter(Unknown Source)
at com.siliconexpert.avago.service.impl.PartDetailServiceImpl.getPackageData(PartDetailServiceImpl.java:170)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:34)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl.getPackageData(Unknown Source)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.ServerRequest.sendReceive(ServerRequest.java:202)
at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:463)
at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:274)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl_12120_WLStub.getPackageData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:84)
at $Proxy111.getPackageData(Unknown Source)
at com.siliconexpert.avago.server.rmi.client.PartDetailServiceRmiClient.getPackageData(PartDetailServiceRmiClient.java:108)
at com.siliconexpert.avago.gui.server.services.PartDetailRemoteServiceImpl.getPackageData(PartDetailRemoteServiceImpl.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at com.siliconexpert.avago.gui.server.services.MainFilter.doFilter(MainFilter.java:47)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3367)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3333)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2220)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2146)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2124)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1564)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)
The above exception is thrown on the below line:
List<TblPkgFeature> list =
em.createNamedQuery("TblPkgFeature.getFeaturesData").setParameter("pkgTypeId", GetFeaturesData.PACKAGE.getCode()).setParameter("type", "package").getResultList();
Also when I changed this method em.createNamedQuery("TblPkgFeature.getFeaturesData") by the method
em.createQuery("select new com.siliconexpert.avago.model.TblPkgFeature(p.fetId, p.fetName, p.fetDisplayName, o.fetDefention, p.unit) " +
" from TblPkgFeature p left outer join p.tblOthersFetDef o where (lower(o.type) =:type or o.type is null )" +
" and p.display=1 and p.pkgTypeId =:pkgTypeId order by p.cmDisplayOrder")
it worked successfully and the exception wasn't thrown.
By the way both queries are the same, but the difference is that I placed the query in the method parameter of the "createQuery()" method.
The below is the entity bean that contains the NamedQuery:
package com.siliconexpert.avago.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* The persistent class for the TBL_PKG_FEATURES database table.
*
*/
#NamedQueries
({
#NamedQuery(name="TblPkgFeature.getFeaturesData", query="select new com.siliconexpert.avago.model.TblPkgFeature(p.fetId, p.fetName, p.fetDisplayName, o.fetDefention, p.unit) " +
" from TblPkgFeature p left outer join p.tblOthersFetDef o where (lower(o.type) =:type or o.type is null )" +
" and p.display=1 and p.pkgTypeId =:pkgTypeId order by p.cmDisplayOrder ") //and p.fetId<>39
})
#Entity
#Table(name = "TBL_PKG_FEATURES")
public class TblPkgFeature implements Serializable
{
private static final long serialVersionUID = -8604710446605212000L;
#Id
#Column(name = "FET_ID")
private long fetId;
#Column(name = "CM_DISPLAY_ORDER")
private long cmDisplayOrder;
#Column(name = "DATA_LENGHT")
private long dataLenght;
#Column(name = "DATA_TYPE")
private String dataType;
private long display;
#Column(name = "FET_DISPLAY_NAME")
private String fetDisplayName;
#Column(name = "FET_HEADER_ORDER")
private long fetHeaderOrder;
#Column(name = "FET_NAME")
private String fetName;
#Column(name = "OLD_NAME")
private String oldName;
#Column(name = "PKG_TYPE_ID")
private long pkgTypeId;
#Column(name = "QUALITY_AV")
private long qualityAv;
#Column(name = "TBL_NAME")
private String tblName;
private String unit;
#OneToOne
#JoinColumn(name="FET_NAME", referencedColumnName="FET_NAME", updatable=false, insertable=false)
private TblOthersFetDef tblOthersFetDef;
#Transient
private String fetDefinition;
public TblPkgFeature()
{
}
public TblPkgFeature(long fetId, String fetDisplayName)
{
super();
this.fetId = fetId;
this.fetDisplayName = fetDisplayName;
}
public TblOthersFetDef getTblOthersFetDef()
{
return tblOthersFetDef;
}
public void setTblOthersFetDef(TblOthersFetDef tblOthersFetDef)
{
this.tblOthersFetDef = tblOthersFetDef;
}
public TblPkgFeature(long fetId, String fetDisplayName, String fetDefinition, String unit)
{
this(fetId, fetDisplayName);
this.fetDefinition = fetDefinition;
this.unit = unit;
}
public TblPkgFeature(long fetId, String fetName, String fetDisplayName, String fetDefinition, String unit)
{
this(fetId, fetDisplayName, fetDefinition, unit);
this.fetName = fetName;
}
public String getFetDefinition()
{
return fetDefinition;
}
public void setFetDefinition(String fetDefinition)
{
this.fetDefinition = fetDefinition;
}
public long getFetId()
{
return this.fetId;
}
public void setFetId(long fetId)
{
this.fetId = fetId;
}
public long getCmDisplayOrder()
{
return this.cmDisplayOrder;
}
public void setCmDisplayOrder(long cmDisplayOrder)
{
this.cmDisplayOrder = cmDisplayOrder;
}
public long getDataLenght()
{
return this.dataLenght;
}
public void setDataLenght(long dataLenght)
{
this.dataLenght = dataLenght;
}
public String getDataType()
{
return this.dataType;
}
public void setDataType(String dataType)
{
this.dataType = dataType;
}
public long getDisplay()
{
return this.display;
}
public void setDisplay(long display)
{
this.display = display;
}
public String getFetDisplayName()
{
return this.fetDisplayName;
}
public void setFetDisplayName(String fetDisplayName)
{
this.fetDisplayName = fetDisplayName;
}
public long getFetHeaderOrder()
{
return this.fetHeaderOrder;
}
public void setFetHeaderOrder(long fetHeaderOrder)
{
this.fetHeaderOrder = fetHeaderOrder;
}
public String getFetName()
{
return this.fetName;
}
public void setFetName(String fetName)
{
this.fetName = fetName;
}
public String getOldName()
{
return this.oldName;
}
public void setOldName(String oldName)
{
this.oldName = oldName;
}
public long getPkgTypeId()
{
return this.pkgTypeId;
}
public void setPkgTypeId(long pkgTypeId)
{
this.pkgTypeId = pkgTypeId;
}
public long getQualityAv()
{
return this.qualityAv;
}
public void setQualityAv(long qualityAv)
{
this.qualityAv = qualityAv;
}
public String getTblName()
{
return this.tblName;
}
public void setTblName(String tblName)
{
this.tblName = tblName;
}
public String getUnit()
{
return this.unit;
}
public void setUnit(String unit)
{
this.unit = unit;
}
}
Please help.
Thanks.

Resources