Getting the error NoSuchMethodError: org.apache.cassandra.thrift.TBinaryProtocol when using Apache Cassandra,Kundera,Spring MVC - spring

I keep getting the message
java.lang.NoSuchMethodError: org.apache.cassandra.thrift.TBinaryProtocol: method <init>(Lorg/apache/thrift/transport/TTransport;)V not found
at com.impetus.client.cassandra.schemamanager.CassandraSchemaManager.initiateClient(CassandraSchemaManager.java:446)
at com.impetus.kundera.configure.schema.api.AbstractSchemaManager.exportSchema(AbstractSchemaManager.java:101)
at com.impetus.client.cassandra.schemamanager.CassandraSchemaManager.exportSchema(CassandraSchemaManager.java:138)
at com.impetus.kundera.configure.SchemaConfiguration.configure(SchemaConfiguration.java:172)
at com.impetus.kundera.configure.ClientMetadataBuilder.buildClientFactoryMetadata(ClientMetadataBuilder.java:45)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configureClientFactories(EntityManagerFactoryImpl.java:352)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:116)
at com.impetus.kundera.KunderaPersistence.createEntityManagerFactory(KunderaPersistence.java:83)
at com.impetus.kundera.KunderaPersistence.createContainerEntityManagerFactory(KunderaPersistence.java:65)
Whenever I try to run my Java Spring MVC 3.2 Project. I am trying to connect to Apache Cassandra 1.2.8 that I have installed on my machine from the Spring WebApp using Kundera. I have included the following dependencies in the pom.xml file of the project:
scale7-pelops(1.3-1.1.x)
cassandra-all & cassandra-clientutil (1.2.8)
kundera-core & kundera-cassandra (2.6)
My Spring Project uses XML-less configuration (Java Config) and JPA apart from kundera's persistence.xml which is under {PROJECT}/src/main/resources/META-INF so as to be at the base of the classpath during deployment. My persistence.xml looks like:
<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="cassandra_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>org.tutiworks.orm.Role</class>
<class>org.tutiworks.orm.User</class>
<properties>
<property name="kundera.nodes" value="localhost"/>
<property name="kundera.port" value="9160"/>
<property name="kundera.keyspace" value="afrikana"/>
<property name="kundera.dialect" value="cassandra"/>
<property name="kundera.ddl.auto.prepare" value="update"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.cassandra.pelops.PelopsClientFactory" />
<property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider"/>
<property name="kundera.cache.config.resource" value="/ehcache-cassandra.xml"/>
</properties>
</persistence-unit>
</persistence>
And the configuration class creating the entityManager looks like:
#Configuration
public class SpringDataConfig extends WebMvcConfigurerAdapter{
#Autowired
private Environment env;
#Value("${kundera.nodes}") private String node;
#Value("${kundera.port}") private String port;
#Value("${kundera.keyspace}") private String keyspace;
#Value("${kundera.dialect}") private String dialect;
#Value("${kundera.ddl.auto.prepare}") private String dbGenerator;
#Value("${kundera.cache.provider.class}") private String cacheClass;
#Value("${kundera.client.lookup.class}") private String lookupClass;
#Value("${kundera.cache.config.resource}") private String configResource;
#Value("${persistence.unit.name}") private String persistenceUnitName;
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName(persistenceUnitName);
return em;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
The following class shows how the persistence context is used.
public abstract class GenericDAO< T extends Serializable > {
private Class<T> clazz;
#PersistenceContext
EntityManager entityManager;
protected void setClazz( Class<T> clazzToSet ){
this.clazz = clazzToSet;
}
public T findOne( String id ){
return this.entityManager.find( this.clazz, id );
}
#SuppressWarnings("unchecked")
public List< T > findAll(){
return this.entityManager.createQuery( "from " + this.clazz.getName() )
.getResultList();
}
public void save( T entity ){
this.entityManager.persist( entity );
}
public void update( T entity ){
this.entityManager.merge( entity );
}
public void delete( T entity ){
this.entityManager.remove( entity );
}
public void deleteById( String entityId ){
T entity = this.findOne( entityId );
this.delete( entity );
}
}
A sample of the ORM that is mapped to a column family in Apache Cassandra installation looks like the following.
#XmlRootElement(name = "Role")
#Entity(name="Role")
#Table(name = "roles", schema = "afrikana#cassandra_pu")
public class Role implements Serializable {
private static final long serialVersionUID = 9127322651789683331L;
#Id
#Column(name="id")
#XmlID
private String id;
#Column(name = "role_name")
#XmlElement(name = "role_name")
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Where would I be going wrong with my configuration? What I'm I missing? How do I fix the error?

Kundera cassandra libraries are running on 1.2.4 version. Ideally 1.2.8 or higher versions should always be backward compatible, but in this case unfortunately they are not!

Related

Save creationTimestamp and updatedTime in spring + hibernate

I need to update the postgres DB with createdDate and updatedDate
I tried using approach 1, But it is inserting null values.
When I read about, it seems the #prepersist annotations does not work for session.
So I decided to go with Approach 2 : Hibernate #CreationTimeStamp Annotation, I added hibernate-annotations maven dependency, But #CreationTimeStamp is not resolved and gives compilation error.
Can someone advise me on how I can resolve the issue ?
Approach 1
Entity class annotated with #Entity and #Table
public class Status{
#Id
#Column(name = "run_id")
private int run_id;
#Column(name = "status")
private String status;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date" , updatable=false)
private Date created;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_date" , insertable=false)
private Date updated;
#PrePersist
protected void onCreate() {
created = new Date();
}
#PreUpdate
protected void onUpdate() {
updated = new Date();
}
//Getters and setters here
}
implementation class is
sessionFactory.getCurrentSession().save(status);
Approach 2
using #CreationTimeStamp and #updatedTimeStamp. But the maven dependency
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-annotations -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.0-Final</version>
</dependency>
does not add these annotations to classpath
Is there a reason you are using the session.save() method instead of an entitymanager? I'll post an example of my application using an entitymanager to persist and merge entities. Also I am using java.time.LocalDateTime instead of java.util.Date, that's why I don't need #Temporal.
This may also help: How to use #PrePersist and #PreUpdate on Embeddable with JPA and Hibernate
If you want to use an entitymanager this will help: Guide to the Hibernate EntityManager
Entity class:
public abstract class AbstractEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(updatable = false, nullable = false)
private Long id;
#Column
private LocalDateTime createdTimestamp;
#Column
private LocalDateTime modifiedTimestamp;
#Version
private Long version;
#PrePersist
public void setCreationDateTime() {
this.createdTimestamp = LocalDateTime.now();
}
#PreUpdate
public void setChangeDateTime() {
this.modifiedTimestamp = LocalDateTime.now();
}
//Getter and setter
}
Abstract database service class:
public abstract class AbstractDatabaseService {
#PersistenceContext(name = "examplePU")
protected EntityManager entityManager;
}
Example Entity Repository Interface:
public interface ExampleRepository {
ExampleEntity save(ExampleEntity exampleEntity);
}
Example Entity Repository Implementation:
public class ExampleRepositoryImpl extends AbstractDatabaseService implements ExampleRepository , Serializable {
#Transactional
#Override
public ExampleEntity save(ExampleEntity exampleEntity) {
ExampleEntity toPersist;
// Updating an already existing entity
if (exampleEntity.getId() != null) {
toPersist = entityManager.find(ExampleEntity .class, exampleEntity.getId());
// Omitted merging toPersist with the given exampleEntity through a mapper class here
} else {
toPersist = exampleEntity;
}
try {
toPersist = entityManager.merge(toPersist);
} catch (Exception e) {
// Logging e
}
return toPersist;
}
}
Hope this helps.

Spring Boot -Hibernate 5 simple application initializing in 3 minutes

I am using Spring boot with Hibernate to connect with Oracle database. The application works fine but when I run the application with Dddl.auto flag set to update it takes 3 minutes just to initialize the entity manager. here are my model classes and cfg.xml.
Hibernate.cfg.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#hhhh.cpckubosallr.ap-south-1.rds.amazonaws.com:1610:gghg</property>
<property name="hibernate.connection.username">DEMO</property>
<property name="hibernate.connection.password">ggggg#78GHTd</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.connection.pool_size">5</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hbm2ddl.auto">update</property>
<mapping class ="student.mappings.model.Student" />
<mapping class ="student.mappings.model.Vehicle" />
<mapping class ="student.mappings.model.Subject" />
</session-factory>
</hibernate-configuration>
Model classes:
#Entity
#Table(name="STUDENT", schema="JAVACODE")
public class Student
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name="name")
private String name;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="vehicle_id")
private Vehicle vehicle;
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", vehicle=" + vehicle + ", subject=" + subject + "]";
}
public Vehicle getVehicle()
{
return vehicle;
}
public void setVehicle(Vehicle vehicle)
{
this.vehicle = vehicle;
}
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="subject_id")
private List<Subject> subject;
public List<Subject> getSubject()
{
return subject;
}
public void setSubject(List<Subject> subject)
{
this.subject = subject;
}
public Student(Long id, String name, Vehicle vehicle, List<Subject> subject)
{
super();
this.id = id;
this.name = name;
this.vehicle = vehicle;
this.subject = subject;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Student()
{
super();
}
public Student(Long id, String name)
{
super();
this.id = id;
this.name = name;
}
public Student(Long id, String name, Vehicle vehicle) {
super();
this.id = id;
this.name = name;
this.vehicle = vehicle;
}
}
Application.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan("student.mappings")
#EntityScan("student.mappings")
#PropertySource(value= {"classpath:application.properties"})
public class StudentMappingsTemplateClient
{
public static void main(String[] args) {
SpringApplication.run(StudentMappingsTemplateClient.class, args);
}
}

Spring Data JPA Redis : Cannot write custom method based query

I have configured Spring Data JPA with Redis and using RedisRepositories with provides methods like find(), findAll() etc. All these methods seem to be working just fine, but I am not able to write my custom method like.
RedisEntity findByGenderAndGrade(String gender, String grade);
RedisEntity is a simple POJO Entity class. If you want any more info, please let me know in messages.
Following is my entity:
#Data
#RedisHash("test1")
public class RedisEntity implements Serializable {
#Id
#GeneratedValue
private String id;
private String name;
private String gender;
private Integer grade;
}
Repository:
#Repository
public interface TestRepository extends JpaRepository<RedisEntity, String> {
List<RedisEntity> findAllByGender(String gender);
List<RedisEntity> findAllByGrade(Integer grade);
}
Service/Controller:
#Override
public List<RedisEntity> getById(String id) {
return testRepository.findById(id); //returns data perfectly.
}
#Override
public List<RedisEntity> getAllByGender(String gender) {
return testRepository.findAllByGender(gender); //returns []
}
#Override
public void saveEntity(RedisEntity redisEntity) {
testRepository.save(redisEntity); // saves it in redis perfectly.
}
Also,
findByGender and findAllByGender both give [], although I can see data in my redis database and save it as well.
As requested by FrançoisDupire,
#Configuration
public class RedisConfig {
#Autowired
private DeploymentProperties deploymentProperties;
private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
#Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
redisStandaloneConfiguration.setPassword(RedisPassword.of("root"));
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
#Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
Also, I had referred this article: Baeldung article on Spring data redis
As mentioned by #JoshJ and verified by myself and others,
The solution to the problem is:
Adding #Indexed annotation
to all those columns/fields which need to be used with all finds.
#Data
#RedisHash("EmployeeDetails")
public class RedisEntity {
#Id
private String employeeId;
private String firstName;
private String lastName;
#Indexed
private String gender;
#Indexed
private String grade;
}
We have the Spring Data Redis Library which provides the scope to write the custom method.Attaching Sample code.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.8.RELEASE</version>
</dependency>
Entity Definition
#Data
#RedisHash("EmployeeDetails")
public class RedisEntity {
#Id
private String employeeId;
private String firstName;
private String lastName;
private String gender;
private String grade;
}
Repository Definition
#Repository
public interface RedisEntityRepository extends CrudRepository<RedisEntity, String>{
List<RedisEntity> findAllByGenderAndGrade(String gender, String grade);
}
Implementation
#Component
public class RedisEntityImpl implements RedisEntityService {
#Autowired
private RedisEntityRepository redisEntityRepository;
#Override
public List<RedisEntity> getAllByGenderAndGrade(String gender, String grade) {
return redisEntityRepository.findAllByGenderAndGrade(gender,grade);
}
}
Properties
spring.cache.type = redis
spring.redis.host = localhost
spring.redis.port = 6379

Why is the child collection is null in One-To-Many relationship of spring boot application?

I create a spring boot application with MySQL,JPA,Web dependencies,and manually config my database settings in .properties file of Spring boot. I passed compiling, and started application successfully, and adding one record is normal fine.
BUT, i use method 'findAll(Pageable pageable)' i got a problem, that was
Could not write JSON: failed to lazily initialize a collection of role,could not initialize proxy - no Session
I got confused, i started to debug my code, finally i found that the child collection of the result is null, and it contained an error, which is
"Exception occurred: com.sun.jdi.InvocationException occurred invoking method.."
I tried a lot to fix my code, but no use.
who can help me?
The entity relationship is a simple one to many:
TeacherInfo entity and ClassInfo entity, teacher manage multiple classes, just simple as this.
here is the enter point of my app:
#SpringBootApplication(exclude= {
DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
DataSourceAutoConfiguration.class
})
#EnableTransactionManagement
public class OrmTestApplication {
public static void main(String[] args) {
SpringApplication.run(OrmTestApplication.class, args);
}
}
Database properties setting is here:
spring.datasource.primary.url=jdbc:mysql://localhost:3306/ormtest?useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=BlaNok2700
spring.datasource.primary.driver-class-name = com.mysql.jdbc.Driver
hibernate.hbm2ddl.auto = update
hibernate.show-sql = true
My Data base configure java code is here:
Configuration
#EnableJpaRepositories(basePackages = "com.lanjian.ormtest.repositories", entityManagerFactoryRef = "primaryEntityManagerFactory", transactionManagerRef = "primaryTransactionManager")
public class PrimaryDbConfig {
#Autowired
private Environment env;
#Bean
#ConfigurationProperties(prefix="spring.datasource.primary")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
public DataSource primaryDataSource() {
DataSourceProperties dbProperty = primaryDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(dbProperty.getDriverClassName())
.url(dbProperty.getUrl())
.username(dbProperty.getUsername())
.password(dbProperty.getPassword())
.build();
}
#Bean
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(primaryDataSource());
factory.setPackagesToScan("com.lanjian.ormtest.entities");
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("hibernate.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
#Bean
public PlatformTransactionManager primaryTransactionManager() {
EntityManagerFactory factory = primaryEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
}
My REST controller method is here:
#Autowired
private TeacherRepository teacherRepository;
#GetMapping("/page")
public Page<TeacherInfo> page(Pageable pageable){
Page<TeacherInfo> list = teacherRepository.findAll(pageable);
return list;
}
What happened
After i started my application, and use postman send request, i got this:
got a 500 error
And i debugger my code, found this:
child collection is null
In the picture, 'classes' is a list collection, but it is null, i don't understand.
Here are the TeacherInfo entity I defined
#Entity
#Table(name = "teacher")
public class TeacherInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private byte age;
private boolean male;
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY, mappedBy="chargedTeacher")
private List<ClassInfo> classes = new ArrayList<>();
public void initialize() {
for (ClassInfo classInfo : classes) {
classInfo.setChargedTeacher(this);
for (StudentInfo studentInfo : classInfo.getStudents()) {
studentInfo.setClassInfo(classInfo);
}
}
}
//Setters and Getters}
Here is the ClassInfo Entity i defined
#Entity
#Table(name = "class_info")
public class ClassInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int capacity;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "teacher_id",nullable=false)
#JsonIgnore
private TeacherInfo chargedTeacher;
#OneToMany(cascade = CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="classInfo")
private List<StudentInfo> students = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public TeacherInfo getChargedTeacher() {
return chargedTeacher;
}
public void setChargedTeacher(TeacherInfo chargedTeacher) {
this.chargedTeacher = chargedTeacher;
}
public List<StudentInfo> getStudents() {
return students;
}
public void setStudents(List<StudentInfo> students) {
this.students = students;
}
}
I think that the problem may come from Transactionality and JPA Fetching types.
Your repository method is being invoked not using a transaction, which implies that the transaction is on the boundaries of the method invocation (which might not be wrong). Spring returns a Page with objects but when it tries to serialize them, transaction is gone so no way to access childs.
I would suggest to put the JPA relationship as EAGER fetching, allowing all the objects to be present on the repository result when the transaction ends.
EDIT:
Answer to comments
#Bean
public PlatformTransactionManager primaryTransactionManager(EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}

OPEN JPA find() could not retrieve the value of the entity from my Database

There is a weird scenario that I had encountered in my User log in program.
Insert the record.. Userid password etc.
Insert the record using merge();
Then close the IDE (Netbeans)
Open IDE Netbeans then start servers, start database connection.
Open the log in browser.
log in using the inserted record.
My program could not detect the record on the table.
When debugging, after the find() it would not populate my entity.. Maybe there is still another step to populate the entity?
LoginAction
package lotmovement.action;
import com.opensymphony.xwork2.ActionSupport;
import lotmovement.business.crud.RecordExistUserProfile;
import org.apache.commons.lang3.StringUtils;
public class LoginAction extends ActionSupport{
private String userName;
private RecordExistUserProfile recordExistUserProfile;
private String password;
#Override
public void validate(){
if(StringUtils.isEmpty(getUserName())){
addFieldError("userName","Username must not be blanks.");
}
else{
if(!recordExistUserProfile.checkrecordexist(getUserName())){
addFieldError("userName","Username don't exist.");
}
}
if(StringUtils.isEmpty(getPassword())){
addFieldError("password","Password must not be blanks.");
}
else{
if(!recordExistUserProfile.CheckPasswordCorrect(getUserName(), getPassword())){
addFieldError("userName","Password not correct");
}
}
}
public String execute(){
return SUCCESS;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public RecordExistUserProfile getRecordExistUserProfile() {
return recordExistUserProfile;
}
public void setRecordExistUserProfile(RecordExistUserProfile recordExistUserProfile) {
this.recordExistUserProfile = recordExistUserProfile;
}
}
Validator Program
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.crud;
import lotmovement.business.entity.UserProfile;
/**
*
* #author god-gavedmework
*/
public class RecordExistUserProfile {
private EntityStart entityStart;
private UserProfile userProfile;
public boolean checkrecordexist(String userId) {
entityStart.StartDbaseConnection();
entityStart.em.find(UserProfile.class, userId);
if (userId.equals(userProfile.getUserId())) {
return true;
} else {
return false;
}
}
public boolean CheckPasswordCorrect(String userId, String password) {
entityStart.StartDbaseConnection();
entityStart.em.find(UserProfile.class, userId);
if (password.equals(userProfile.getPassword())) {
return true;
} else {
return false; ---> It will step here.
}
}
public UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
public EntityStart getEntityStart() {
return entityStart;
}
public void setEntityStart(EntityStart entityStart) {
this.entityStart = entityStart;
}
}
Entity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.entity;
import java.io.Serializable;
import javax.persistence.*;
/**
*
* #author god-gavedmework
*/
#Entity(name = "USERPROFILE") //Name of the entity
public class UserProfile implements Serializable{
#Id //signifies the primary key
#Column(name = "USER_ID", nullable = false,length = 20)
private String userId;
#Column(name = "PASSWORD", nullable = false,length = 20)
private String password;
#Column(name = "FIRST_NAME", nullable = false,length = 20)
private String firstName;
#Column(name = "LAST_NAME", nullable = false,length = 50)
private String lastName;
#Column(name = "SECURITY_LEVEL", nullable = false,length = 4)
private int securityLevel;
#Version
#Column(name = "LAST_UPDATED_TIME")
private java.sql.Timestamp updatedTime;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
public int getSecurityLevel() {
return securityLevel;
}
public void setSecurityLevel(int securityLevel) {
this.securityLevel = securityLevel;
}
public java.sql.Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(java.sql.Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
}
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.crud;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import lotmovement.business.entity.UserProfile;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
public class EntityStart {
EntityManagerFactory factory;
EntityManager em;
public void StartDbaseConnection()
{
factory = Persistence.createEntityManagerFactory("LotMovementPU");
em = factory.createEntityManager();
}
public void StartPopulateTransaction(Object entity){
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.merge(entity);
userTransaction.commit();
em.close();
}
public void CloseDbaseConnection(){
factory.close();
}
}
Using Trace as adviced, This is the log of the SQL
SELECT t0.LAST_UPDATED_TIME, t0.FIRST_NAME, t0.LAST_NAME, t0.PASSWORD, t0.SECURITY_LEVEL FROM USERPROFILE t0 WHERE t0.USER_ID = ? [params=(String) tok]
This is the record:
USER_ID FIRST_NAME LAST_NAME PASSWORD SECURITY_LEVEL LAST_UPDATED_TIME
tok 1 1 1 1 2012-12-13 08:46:48.802
Added Persistence.XML
<persistence version="2.0" 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">
<persistence-unit name="LotMovementPU" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<non-jta-data-source/>
<class>lotmovement.business.entity.UserProfile</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:derby://localhost:1527/LotMovementDBase"/>
<property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="openjpa.ConnectionUserName" value="toksis"/>
<property name="openjpa.ConnectionPassword" value="bitoytoksis"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
</properties>
</persistence-unit>
</persistence>
I discovered the root cause of the problem. It is on how I instantiate the class in Spring Plugin.
When I change the find() statement to below, it will now work.
UserProfile up = entityStart.em.find(UserProfile.class, "tok");
But how can i initialize this one using Spring? codes below dont work?
private UserProfile userProfile;
...... some codes here.
entityStart.em.find(UserProfile.class, userId);
..... getter setter
The Root cause of the problem.
entityStart.em.find(UserProfile.class, userId); --> it should be
userProfile = entityStart.em.find(UserProfile.class, userId);

Resources