I have got a JavaFX application, which gets access to MySQL database with the help of JPA technology.
Here is how I create and use entity manager in my application:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerHelper {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
static {
if (InitPersistence.persistenceMap != null && InitPersistence.getNewIP() != null)
emf = Persistence.createEntityManagerFactory("TonalityJPA",
InitPersistence.persistenceMap);
else
emf = Persistence.createEntityManagerFactory("TonalityJPA");
threadLocal = new ThreadLocal<EntityManager>();
}
public static EntityManager getEntityManager() {
EntityManager em = threadLocal.get();
if (em == null) {
em = emf.createEntityManager();
// set your flush mode here
threadLocal.set(em);
}
return em;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
if (em != null) {
em.close();
threadLocal.set(null);
}
}
public static void closeEntityManagerFactory() {
emf.close();
}
public static void begin() {
getEntityManager().getTransaction().begin();
}
public static <T> void remove(T thingToRemove) {
getEntityManager().remove(thingToRemove);
}
public static <T> void persist(T thingToPersist) {
getEntityManager().persist(thingToPersist);
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static <T> T find(Class<T> a, long id) {
return getEntityManager().find(a, id);
}
}
I took this class from the answer to this post JAVA: an EntityManager object in a multithread environment and added some functions to it.
My application goes through authorization through DB, then shows the list of users from DB.
Application user chooses one of them and deletes him.
Here how it works:
delBtn.setOnAction(event -> {
long id = currentUser.getUserId();
new UserActions().delete(id);
UserLogEntity userLog = new UserLogEntity(UserData.getUser().getUserId(), "deleted user: " +
currentUser.getUserLogin(), 3, new Date());
UserLogActions log_action = new UserLogActions();
log_action.add(userLog);
} else {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Помилка");
alert.setHeaderText("");
alert.setContentText("Оберіть користувача для видалення");
alert.showAndWait();
}
});
And here are the UserEntity and UserActions classes:
UserEntity:
package com.Model.DataBase.Entities;
import org.mindrot.jbcrypt.BCrypt;
import javax.persistence.*;
/**
* Created by User on 07.03.2016.
*/
#Entity
#Table(name = "user", schema = "newsmonitoringdb")
public class UserEntity {
private Long userId;
private String userLogin;
private String userPass;
private int userAccessLvl;
public UserEntity(){}
public UserEntity(String login, String pass, int accessLvl)
{
this.userLogin = login;
this.userPass = pass;
this.userAccessLvl = accessLvl;
}
#Id
#Column(name = "userID")
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#Basic
#Column(name = "userLogin")
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
#Basic
#Column(name = "userPass")
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
#Basic
#Column(name = "userAccessLvl")
public int getUserAccessLvl() {
return userAccessLvl;
}
}
UserAction:
package com.Model.DataBase.EntitiesActions;
import com.Model.DataBase.Entities.UserEntity;
import com.Model.DataBase.EntityManagerHelper;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
public class UserActions{
public List<UserEntity> list() {
Query query = EntityManagerHelper.getEntityManager().createQuery("SELECT a FROM UserEntity a", UserEntity.class);
return (List <UserEntity>) query.getResultList();
}
public void add(UserEntity user) {
try {
EntityManagerHelper.begin();
EntityManagerHelper.persist(user);
EntityManagerHelper.commit();
} catch (Exception ex) {
//entityManager.getTransaction().rollback();
//ex.printStackTrace();
}
}
public void delete(long id) {
try {
UserEntity user = EntityManagerHelper.find(UserEntity.class, id);
EntityManagerHelper.begin();
EntityManagerHelper.remove(user);
EntityManagerHelper.commit();
} catch (Exception ex) {
ex.printStackTrace();
EntityManagerHelper.rollback();
}
}
}
In case if I have
EntityManagerHelper.begin();
in delete method, I am send to the catch block at this line with two exceptions:
javax.persistence.RollbackException: Transaction marked as rollbackOnly
and
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: Transaction not active
I understand the first one, but the second one is unexpected.
if I take away this line, I enter the catch block from the line:
EntityManagerHelper.commit();
The first exception is the same, the second exception is
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: Transaction not active
How can I solve this issue to get no exceptions?
Related
While running the spring-application I got the following exception:
java.lang.ClassCastException: project.db.dbmodels.Permission cannot be cast to project.db.dbmodels.Permission
at project.db.DataOperator.setUpDefaultPermission(DataOperator.java:573)
at project.web.WebController.start(WebController.java:18)
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:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
...
I can't recreate this Exception, while running Unit Tests.
Those are my classes:
Permission:
package project.db.dbmodels;
import java.util.*;
import javax.persistence.*;
#Entity
#Table(name = "permission")
public class Permission {
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy = "permission", cascade = CascadeType.ALL)
private Set<Permission_PermissionRole> permissionPermissionRole = new HashSet<Permission_PermissionRole>();
public Permission() {
}
public Permission(int id, String name, Set<Permission_PermissionRole> permissionPermissionRole) {
this.id = id;
this.name = name;
this.permissionPermissionRole = permissionPermissionRole;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Permission_PermissionRole> getPermissionPermissionRole() {
return this.permissionPermissionRole;
}
public void setPermissionPermissionRole(Set<Permission_PermissionRole> permissionPermissionRole) {
this.permissionPermissionRole = permissionPermissionRole;
}
public void addPermissionPermissionRole(Permission_PermissionRole permissionPermissionRole) {
this.permissionPermissionRole.add(permissionPermissionRole);
}
public Permission id(int id) {
this.id = id;
return this;
}
public Permission name(String name) {
this.name = name;
return this;
}
public Permission permissionPermissionRole(Set<Permission_PermissionRole> permissionPermissionRole) {
this.permissionPermissionRole = permissionPermissionRole;
return this;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Permission)) {
return false;
}
Permission permission = (Permission) o;
return id == permission.id && Objects.equals(name, permission.name)
&& Objects.equals(permissionPermissionRole, permission.permissionPermissionRole);
}
#Override
public int hashCode() {
return Objects.hash(id, name);
}
#Override
public String toString() {
return "{" + " id='" + getId() + "'" + ", name='" + getName() + "'" + "}";
}
}
DataOperator:
package project.db;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import project.db.dbmodels.*;
import org.apache.log4j.Logger;
public class DataOperator {
final static Logger log = Logger.getLogger(DataOperator.class);
private static boolean setUpDefaultPermission(boolean change) {
SessionFactory sf = HibernateUtil.getSessionFactory();
if (sf == null) {
return false;
}
Session session = sf.openSession();
session.beginTransaction();
boolean arePermissionsReady = true;
// Setup permission "AcessAdminarea"
String request = "FROM Permission WHERE name = 'Acess Adminarea'";
Query<Permission> query = session.createQuery(request, Permission.class);
query.setMaxResults(1);
Permission permAdminArea = null;
try {
permAdminArea = query.uniqueResult();//The Exception occures here
} catch (PersistenceException e) {
return false;
}
if (permAdminArea == null) {
arePermissionsReady = false;
if (change) {
permAdminArea = new Permission();
permAdminArea.setName("Acess Adminarea");
session.save(permAdminArea);
}
}
// Setup permissionrole "Admin"
request = "FROM PermissionRole WHERE name = 'Admin'";
Query<PermissionRole> query2 = session.createQuery(request, PermissionRole.class);
PermissionRole roleAdmin = null;
try {
roleAdmin = query2.uniqueResult();
} catch (PersistenceException e) {
return false;
}
if (roleAdmin == null) {
arePermissionsReady = false;
if (change) {
roleAdmin = new PermissionRole();
roleAdmin.setName("Admin");
session.save(roleAdmin);
Permission_PermissionRole permPermrole = new Permission_PermissionRole();
permPermrole.setPermission(permAdminArea);
permPermrole.setRole(roleAdmin);
session.save(permPermrole);
}
}
// Setup permissionrole "Employee"
request = "FROM PermissionRole WHERE name = 'Employee'";
query2 = session.createQuery(request, PermissionRole.class);
PermissionRole roleEmployee = null;
try {
roleEmployee = query2.uniqueResult();
} catch (PersistenceException e) {
return false;
}
if (roleEmployee == null) {
arePermissionsReady = false;
if (change) {
roleEmployee = new PermissionRole();
roleEmployee.setName("Employee");
session.save(roleEmployee);
}
}
if (change && !arePermissionsReady) {
try {
session.getTransaction().commit();
arePermissionsReady = true;
} catch (IllegalStateException e) {
log.error(String.format("Unable to commit the transaction : %s", e.getMessage()));
} catch (RollbackException e) {
log.error(String.format("Unable to commit the transaction : %s", e.getMessage()));
}
session.close();
}
return arePermissionsReady;
}
}
While looking for the error I tried to get me some more Debug content, so I replaced the line, where the Exception ocurred and I inserted the following code into DataOperator:
Object result = query.uniqueResult();
String resultType = result.getClass().toString();
boolean test = result instanceof Permission;
boolean test2 = Permission.class.toString().equals(resultType);
I set a stop after this segment and when debugging while running it with Spring I got:
result: Permission#47 "{ id='15', name='Acess AdminArea'}"
resultType: "class project.db.dbmodels.Permission"
test: false
test2: true
While running a unit test i got:
result: Permission#47 "{ id='15', name='Acess AdminArea'}"
resultType: "class project.db.dbmodels.Permission"
test: true
test2: true
Edit: They have different class loaders. sun.misc.Launcher$AppCLassLoader and org.springframework.boot.devtools.restart.classloader.RestartClassLoader.
What can I do about that?
As mentioned by Ed Schaller in another response the problem came from the fact that the classes were loaded from two different entities.
Although, instead of changing the classpath, I found a way to fix this by using a BootstrapServiceRegistry and adding the class loaders of both the application and hibernate.
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder(
createHibernateBootstrapServiceRegistry()).configure().build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
private static BootstrapServiceRegistry createHibernateBootstrapServiceRegistry() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
ClassLoader hibernateCl = BootstrapServiceRegistry.class.getClassLoader();
return new BootstrapServiceRegistryBuilder().applyClassLoader(tccl).applyClassLoader(hibernateCl).build();
}
public static Session openSession() {
return sessionFactory.openSession();
}
}
This happens when the class in question is being loaded from two (or more) class loaders. A class in java is only unique when combined with it's class loader. Likely your Permission class is getting loaded from one class loader and then it is being cast to the same class but loaded from a different class loader.
Add the class loader to your debug logs and you'll likely see the problem and hopefully which class loaders the class is being loaded by.
I'm new to spring hybernate.
I got the following exception.
could anyone can help....
org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:262)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:44)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:71)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:267)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:338)
at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:785)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:721)
at org.hibernate.loader.Loader.processResultSet(Loader.java:953)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
Here is the model class
DashModel.java
#Entity
#Table(name = "VIEW_GENERAL_SALES_DASHBOARD")
#DynamicUpdate(true)
public class DashModel implements Serializable {
private static final long serialVersionUID = -3465813074586302847L;
public DashModel() {
System.out.println("VIEW_GENSALES_DASH....");
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column
private Integer VIEW_ROW;
public Integer getVIEW_ROW() {
return VIEW_ROW;
}
public void setVIEW_ROW(Integer vIEW_ROW) {
VIEW_ROW = vIEW_ROW;
}
#Column
private String VIEW_CLASS;
#Column
private String VIEW_ZONE;
#Column
private double VIEW_GWP;
#Column
private double VIEW_TARGET;
#Column
private double VIEW_VARIANCE;
#Column
private double VIEW_ACHIEVEMENT;
public String getVIEW_CLASS() {
return VIEW_CLASS;
}
public void setVIEW_CLASS(String vIEW_CLASS) {
VIEW_CLASS = vIEW_CLASS;
}
public String getVIEW_ZONE() {
return VIEW_ZONE;
}
public void setVIEW_ZONE(String vIEW_ZONE) {
VIEW_ZONE = vIEW_ZONE;
}
public double getVIEW_GWP() {
return VIEW_GWP;
}
public void setVIEW_GWP(double vIEW_GWP) {
VIEW_GWP = vIEW_GWP;
}
public double getVIEW_TARGET() {
return VIEW_TARGET;
}
public void setVIEW_TARGET(double vIEW_TARGET) {
VIEW_TARGET = vIEW_TARGET;
}
public double getVIEW_VARIANCE() {
return VIEW_VARIANCE;
}
public void setVIEW_VARIANCE(double vIEW_VARIANCE) {
VIEW_VARIANCE = vIEW_VARIANCE;
}
public double getVIEW_ACHIEVEMENT() {
return VIEW_ACHIEVEMENT;
}
public void setVIEW_ACHIEVEMENT(double vIEW_ACHIEVEMENT) {
VIEW_ACHIEVEMENT = vIEW_ACHIEVEMENT;
}
}
Here is the dao class
DashDao.java
#Repository
public class DashDao {
Connection con;
Statement st;
ResultSet rs;
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
System.out.println("setSessionFactory ()");
}
public DashDao() {
System.out.println("Dash dao ()");
}
//this code is to load all the companies
public List<DashModel> getAllCompany() {
List<DashModel> companees = null;
//Session session = sessionFactory.openSession();
Session session = sessionFactory.getCurrentSession();
org.hibernate.Transaction tx = null;
try {
System.out.println("connect ");
tx = session.beginTransaction();
companees= session.createQuery("from DashModel").list();
tx.commit();
} catch (Exception e) {
System.out.println("Error ");
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
return null;
}
return companees;
}
}
Here is service DashService.java
#Service("dashservice")
public class DashService {
#Autowired
DashDao dashdao;
public DashService() {
System.out.println("Dash service()");
}
#Transactional
public List<DashModel> getAllCompany(){
return(dashdao.getAllCompany());
}
}
Here is my controller class
DashController.java
#Controller
public class DashController {
#Autowired
DashService dashservice;
private static final Logger logger = Logger
.getLogger(DashController.class);
public DashController() {
System.out.println("Dash Controller()");
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView listPersonsre(Model model, HttpSession session, HttpServletRequest request) {
System.out.println("I am hear in / request");
ModelAndView md = null;
md= new ModelAndView("dashboard");
return md;
}
// this code is to retrive all companys.
#RequestMapping(value = "/companylist", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<DashModel> companyList(#ModelAttribute #Valid DashModel company, BindingResult result,
ModelAndView model) {
System.out.println("company List");
List<DashModel> companyList = new ArrayList<DashModel>();
return dashservice.getAllCompany();
}
}
And this is my database view
CREATE OR REPLACE VIEW VIEW_GENERAL_SALES_DASHBOARD ( VIEW_ROW,
VIEW_CLASS, VIEW_ZONE, VIEW_GWP, VIEW_TARGET,
VIEW_VARIANCE, VIEW_ACHIEVEMENT, VIEW_GROWTH )
There's no primary key in this view.thats why i create a ROWNUM to the view.
I hope in your help and suggestions!
thanks....
I am new in Spring-Hibernate and my issue is : a transaction is not saving the data in the table. But not throwing any exception as well. From the line
Long id = logTransactionFileUpload(fileMetdataBean);
in the function "logClientFile" (in the "Transactional" annotated class/service class, listed below), I am seeing a returned id but data did not show up in the table. .
Finding is : this is nested transaction and was rolled back as the parent had exception from "msgProducer.send( message, jmsConnectInfo )" in JobRunnerServiceImpl class , in submitJob method- means after db insertion. Is there a way that hibernate can persist child transacttion when parent fails?
I am not suspecting my spring/hibernate configuration as save from other parts are working fine. Only this part is the problem.
FYI:
if I turn on ( in the DAO impl class, listed below)
//getCurrentSession().flush();
//getCurrentSession().getTransaction().commit();
Then data is showing up in the table.But this commit and flush should not be there when #transactional is used.
My #Transactional annotated class:
#Service("jobRunnerService")
#Transactional
public class JobRunnerServiceImpl implements JobRunnerService
{
private static final Logger LOG = LoggerFactory.getLogger( MethodHandles.lookup().lookupClass() );
#Autowired
#Qualifier("fileLoggerDao")
private IFileLoggerDAO fileLoggerDAO;
#Autowired
#Qualifier("fileMetaDataDao")
private IGenericDAO<FileMetaDataBean,Long> fileMetaDataDAO;
public void submitJob(String serviceName, String filePath, long clientId, long layoutId, String audienceId,
boolean isCA)
{
Map<String, String> parameters = new HashMap<String, String>();
try
{
..... doing something............
LOG.info( "Logging file information in FILE_META_DATA table... " );
String loggedFile = logClientFile( fileName, FACEBOOK_FILE_TYPE, fileExt, clientId, tpList );
..... doing something............
LOG.info( " Submitting job to JMS Q...." );
msgProducer.send( message, jmsConnectInfo );
//test code for the receiver to see if sent messages are received by receiver
//WildFlyJmsQueueReceive receiver = new WildFlyJmsQueueReceive();
//receiver.receiveMessagesFromQueue();
}
catch ( Exception e )
{
String msg = "Error in JobRunnerServiceImpl.submitJob";
LOG.error(msg,e);
throw new RuntimeException(msg,e);
}
}
private String logClientFile( String fileName, String fileType, String fileExt, long clientId, List<ToolkitPropertyBean> tpList )
{
ApplicationEnvironment enviro;
try
{
..... doing something............
//insert record in FILE_META_DATA table
FileMetaDataBean fileMetdataBean = new FileMetaDataBean(fileId, new Long(fileTypeID), fileName, fbFilePickUpDir +java.nio.file.FileSystems.getDefault().getSeparator()+ currentFile.getName(), receivedDate,new Long( FileUtilities.getRecordCount( currentFile ) ).longValue(), clientId);
Long id = logTransactionFileUpload(fileMetdataBean);
return null;
}
catch ( Exception e )
{
String msg = "Inside JobRunnerServiceImpl.logClientFile - Unable to log client file";
LOG.error(msg,e);
throw new RuntimeException(msg,e);
}
}
private Long logTransactionFileUpload(FileMetaDataBean bean)
{
return (Long)fileMetaDataDAO.save(bean);
}
}
My bean :
#Entity
#Table(name="FILE_META_DATA", schema = "OAP_META_OWNER", uniqueConstraints = {
#UniqueConstraint(columnNames = "file_meta_data_id"),
})
//#SequenceGenerator(name="file_meta_seq", sequenceName="file_meta_seq")
public class FileMetaDataBean implements Serializable
{
private long fileMetaDataId;
private Long fileType;
private String fileName;
private String originaFileName;
private Date receivedDt;
private Long recordCount;
private Long clientId;
public FileMetaDataBean(){}
public FileMetaDataBean( long fileMetaDataId, Long fileType, String fileName, String originaFileName, Date receivedDt,
long recordCount, long clientId )
{
super();
this.fileMetaDataId = fileMetaDataId;
this.fileType = fileType;
this.fileName = fileName;
this.originaFileName = originaFileName;
this.receivedDt = receivedDt;
this.recordCount = recordCount;
this.clientId = clientId;
}
#Id
// #GeneratedValue(strategy = GenerationType.AUTO, generator = "file_meta_seq")
#Column(name = "file_meta_data_id", unique = true, nullable = false)
public long getFileMetaDataId()
{
return fileMetaDataId;
}
public void setFileMetaDataId( long fileMetaDataId )
{
this.fileMetaDataId = fileMetaDataId;
}
#Column(name = "file_type_id", unique = false, nullable = false)
public Long getFileType()
{
return fileType;
}
public void setFileType( Long fileType )
{
this.fileType = fileType;
}
#Column(name = "file_name", unique = false, nullable = false)
public String getFileName()
{
return fileName;
}
public void setFileName( String fileName )
{
this.fileName = fileName;
}
#Column(name = "original_file_name", unique = false, nullable = false)
public String getOriginaFileName()
{
return originaFileName;
}
public void setOriginaFileName( String originaFileName )
{
this.originaFileName = originaFileName;
}
#Column(name = "received_dt", unique = false, nullable = false)
public Date getReceivedDt()
{
return receivedDt;
}
public void setReceivedDt( Date receivedDt )
{
this.receivedDt = receivedDt;
}
#Column(name = "record_count", unique = false, nullable = false)
public Long getRecordCount()
{
return recordCount;
}
public void setRecordCount( Long recordCount )
{
this.recordCount = recordCount;
}
#Column(name = "client_id", unique = false, nullable = false)
public Long getClientId()
{
return clientId;
}
public void setClientId( Long clientId )
{
this.clientId = clientId;
}
}
The DAO interface
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
public interface IGenericDAO< Entity extends Serializable, ID extends Serializable >
{
Entity getById( ID id );
List<Entity> getAll();
List<Entity> getAll( String contraints);
List<Entity> search( Map<String, Object> parms );
ID save( Entity entity );
void saveOrUpdate( Entity entity );
void update( Entity entity );
void delete( Entity entity );
void deleteById( ID id );
void setSessionFactory( SessionFactory sessionFactory );
void setEntity( final Class clazz );
}
The DAO impl:
#SuppressWarnings(value = "unchecked")
public class GenericDAOImpl<Entity extends Serializable, ID extends Serializable>
implements IGenericDAO<Entity, ID> {
protected Class<Entity> clazz;
public GenericDAOImpl(Class<Entity> clazz) {
System.out.println(this.getClass().getSimpleName() + " called");
this.clazz = clazz;
}
#Autowired
#Qualifier("sessionFactory")
protected SessionFactory sessionFactory;
#Override
public Entity getById(ID id) {
System.out.println("GenericHibernateDAO.getById called with id: " + id);
return (Entity) getCurrentSession().get(clazz, id);
}
#Override
public List<Entity> getAll() {
System.out.println("GenericHibernateDAO.getAll called");
return getCurrentSession().createCriteria(clazz.getName()).list();
// return getCurrentSession().createQuery("from " + clazz.getName()).list();
}
#Override
public List<Entity> getAll(String contraints) {
System.out.println("GenericHibernateDAO.getAll called. Constraint : " + contraints);
return getCurrentSession().createQuery("from " + clazz.getName() + " " + contraints ).list();
}
#Override
public List search(Map<String, Object> parms) {
Criteria criteria = getCurrentSession().createCriteria(clazz);
for (String field : parms.keySet()) {
criteria.add(Restrictions.ilike(field, parms.get(field)));
}
return criteria.list();
}
#Override
public ID save(Entity entity) {
Serializable id = null;
try
{
id = getCurrentSession().save(entity);
}
catch(RuntimeException e)
{
throw e;
}
// getCurrentSession().flush();
// getCurrentSession().getTransaction().commit();
return (ID)id;
}
#Override
public void saveOrUpdate(Entity entity) {
getCurrentSession().saveOrUpdate(entity);
getCurrentSession().flush();
getCurrentSession().getTransaction().commit();
}
#Override
public void update(Entity entity) {
getCurrentSession().update(entity);
getCurrentSession().flush();
getCurrentSession().getTransaction().commit();
}
#Override
public void delete(Entity entity) {
getCurrentSession().delete(entity);
getCurrentSession().flush();
getCurrentSession().getTransaction().commit();
}
#Override
public void deleteById(ID id) {
delete(getById(id));
}
protected Session getCurrentSession() {
// return sessionFactory.openSession();
return sessionFactory.getCurrentSession();
}
#Override
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void setEntity(final Class clazz) {
this.clazz = clazz;
}
}
You can use the
noRollbackFor
property of Transactional annotation something like e.g. #Transactional(noRollbackFor=SendMsgFailureException.class). You need to handle the exception of the parent caller method for which you indent not to rollback.
I am new to play framework and I have project with java in play framework connected to the mongoDB via MorphiaPlay. My problem is that I cannot add data. This is some of my code
public class Sign extends Controller{
static Form<Group> groupForm = form(Group.class);
public static Result index() throws Exception {
// redirect to the "group Result
return redirect(routes.Sign.group());
}
public static Result group() {
return ok(views.html.sign.render(Group.all(), groupForm));
}
public static Result newGroup() {
Form<Group> filledForm = groupForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(views.html.sign.render(Group.all(), filledForm));
} else {
Group.create(filledForm.get());
return redirect(routes.Sign.group());
}
}
}
#Entity
public class Group {
#Id
public ObjectId id;
#Required
public String name;
public String email;
public String username;
public String password;
public static List<Group> all() {
if (MorphiaObject.datastore != null) {
return MorphiaObject.datastore.find(Group.class).asList();
} else {
return new ArrayList<Group>();
}
}
public static void create(Group group) {
MorphiaObject.datastore.save(group);
}
And the error is
Execution exception
[NullPointerException: null]
In C:\lo\app\models\Group.java at line 37.
public static void create(Group group) {
MorphiaObject.datastore.save(group);
}
My morphiaObject class
package controllers;
public class MorphiaObject extends GlobalSettings{
static public Mongo mongo;
static public Morphia morphia;
static public Datastore datastore;
#Override
public void onStart(play.Application arg0) {
super.beforeStart(arg0);
Logger.debug("** onStart **");
try {
MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "project");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
Logger.debug("** Morphia datastore: " + MorphiaObject.datastore.getDB());
}
}
Can you please help!
i am wondering if you could help me
basically i have created a db, and it adds data to two pieces of data to the table, leaving the rest of the columns blank, what i want to do, is be able to update these records with some more data for the blank columns, how can i achieve this ?
this is my code atm, but i just get a null point error and don't know if im doing it right
This is the u.i.
<p>
Student Number : <!--More for me than anything -->
<h:inputText value="#{editMarkingBean.markSectionTwo.studentNumber}" />
</p>
this is where the student number is entered, this is what i want to update, the record that contains this student number (no way can there be more than one of the same username )
<p:spinner id="ajaxspinner80-100" value="#{editMarkingBean.markSectionTwo.markSectionTwo}"
stepFactor="1" min="80" max="100" disabled="#{formBean.number != 8}">
<p:ajax update="ajaxspinnervalue" process="#this" />
</p:spinner>
this is the value i want to add to the column markSectionTwo
the save button
<p:commandButton action="#{editMarkingBean.markSectionTwo}" value="#{bundle.buttonSave}" update=":growl" icon="ui-icon-disk"/>
the backing bean :
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
and this is the entity for the table creation
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentNumber,markingStage, markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, markSectionFive, overalMark, plagorism, feedback, comments;
i get the error
WARNING: javax.el.PropertyNotFoundException: /lecturer/marking/marking-section-two.xhtml #109,82 value="#{editMarkingBean.markSectionTwo.markSectionTwo}": Target Unreachable, 'null' returned null
how can i update the records based on the student number ?
Thanks guys
EDIT
here is the complete editMarkingController class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sws.control;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import sws.business.MarkingService;
import sws.entities.Marking;
import sws.persistance.MarkingFacade;
/**
*
* #author Richard
*/
#Named(value = "editMarkingBean")
#ViewScoped
public class EditMarkingController {
private String searchString;
private String ordering;
private String criteria;
private String match;
private Date today;
private String caseMatch;
private int spinnerField;
private Marking markSectionOne;
private Marking studentNumber;
private Marking markSectionTwo;
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
/*
public String markSectionOne() {
//supposing the data in markSectionOne is filled...
this.markingFacade.create(markSectionOne);
this.setMessage("Mark Saved");
//after saving...
markSectionOne = new Marking();
// now navigating to the next page
return "/lecturer/marking/marking-section-two";
}
*/
public void editMark() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
public Marking getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(Marking markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getOrdering() {
return ordering;
}
public void setOrdering(String ordering) {
this.ordering = ordering;
}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getMatch() {
return match;
}
public void setMatch(String match) {
this.match = match;
}
public Date getToday() {
return today;
}
public void setToday(Date today) {
this.today = today;
}
public String getCaseMatch() {
return caseMatch;
}
public void setCaseMatch(String caseMatch) {
this.caseMatch = caseMatch;
}
public int getSpinnerField() {
return spinnerField;
}
public void setSpinnerField(int spinnerField) {
this.spinnerField = spinnerField;
}
public Marking getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(Marking markSectionOne) {
this.markSectionOne = markSectionOne;
}
public Marking getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(Marking studentNumber) {
this.studentNumber = studentNumber;
}
public MarkingService getMarkingService() {
return markingService;
}
public void setMarkingService(MarkingService markingService) {
this.markingService = markingService;
}
public MarkingFacade getMarkingFacade() {
return markingFacade;
}
public void setMarkingFacade(MarkingFacade markingFacade) {
this.markingFacade = markingFacade;
}
}
the complete marking service
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Inject;
import sws.entities.Marking;
import sws.entities.ProjectIdea;
import sws.persistance.MarkingFacade;
import sws.persistance.PersonFacade;
/**
*
* #author Richard
*/
public class MarkingService {
#EJB
private MarkingFacade markingFacade;
public List<Marking> getAllMarks() {
return markingFacade.findAll();
}
}
and comeplte marking entity
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sws.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* #author Richard
*/
#Entity(name = "MARKING")
public class Marking implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentNumber,markingStage, markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, markSectionFive, overalMark, plagorism, feedback, comments;
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public String getMarkingStage() {
return markingStage;
}
public void setMarkingStage(String markingStage) {
this.markingStage = markingStage;
}
public String getMarkingCompleted() {
return markingCompleted;
}
public void setMarkingCompleted(String markingCompleted) {
this.markingCompleted = markingCompleted;
}
public String getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(String markSectionOne) {
this.markSectionOne = markSectionOne;
}
public String getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(String markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getMarkSectionThree() {
return markSectionThree;
}
public void setMarkSectionThree(String markSectionThree) {
this.markSectionThree = markSectionThree;
}
public String getMarkSectionFour() {
return markSectionFour;
}
public void setMarkSectionFour(String markSectionFour) {
this.markSectionFour = markSectionFour;
}
public String getMarkSectionFive() {
return markSectionFive;
}
public void setMarkSectionFive(String markSectionFive) {
this.markSectionFive = markSectionFive;
}
public String getOveralMark() {
return overalMark;
}
public void setOveralMark(String overalMark) {
this.overalMark = overalMark;
}
public String getPlagorism() {
return plagorism;
}
public void setPlagorism(String plagorism) {
this.plagorism = plagorism;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Marking)) {
return false;
}
Marking other = (Marking) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "sws.entities.Marking[ id=" + id + " ]";
}
public void setmarkSectionOne(String markSectionOne) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
EDIT 2:
i have added a postconstruct
#PostConstruct
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
}
but now i get the error message http 500 error
javax.servlet.ServletException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.markSectionTwo() on sws.control.EditMarkingController#44de1491
root cause
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.markSectionTwo() on sws.control.EditMarkingController#44de1491
root cause
java.lang.reflect.InvocationTargetException
root cause
javax.ejb.EJBException
root cause
java.lang.IllegalArgumentException: Object: null is not a known entity type.
when i try to load the page
EDIT 3
i have fixed that issue, but now i am only able to add the record, what i am trying to do is merge the records, so if the studentNumber is the same as already in the table then update the markSectionTwo to this value rather than creating a new row in the db for it
private Marking markSectionTwo;
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
#PostConstruct
public void init() {
this.markSectionTwo = new Marking();
}
public String markSectionTwo() {
//supposing the data in markSectionOne is filled...
//markSectionOne.setMarkSectionOne("markSectionOne");
//markSectionTwo.setMarkSectionTwo("markSectionTwo");
this.markingFacade.edit(markSectionTwo);
this.setMessage("Mark Saved");
//after saving...
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
// now navigating to the next page
return "/lecturer/marking/marking-section-two";
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
your error message
javax.el.PropertyNotFoundException (...) #{editMarkingBean.markSectionTwo.markSectionTwo}"
basically says that you must have
a managed bean called editMarkingBean
an object in your managed bean called markSectionTwo with proper getter and setter
an attribute in your object markSectionTwo called markSectionTwo with proper getter and setter
so what EL is trying to call is
editMarkingBean.getMarkSectionTwo().getMarkSectionTwo()
please check all your classes and, if possible, post all the relevant parts in your question, such as classes names (all of them), managed bean scope annotations, getters and setters and attributes.