Not able to update tinyint field - java

Hi I am not able to update msgFromUserFlag in database through hibernate. Neither i am getting any error while updating this value.
This is my code at DAO layer. and in database my field is of TINYINT(1) type and in persistence class it is of type boolean.
public void updateMsgFromUserFlag(CustomerOrder customerOrderEntity){
try {
//update(customerOrderEntity);
final StringBuffer queryString = new StringBuffer("update CustomerOrder custOrder set custOrder.msgFromUserFlag = :param1 where custOrder.goldOrderNumber = :param2");
final Query query = this.getEm().createQuery(queryString.toString());
query.setParameter("param1",customerOrderEntity.isMsgFromUserFlag());
query.setParameter("param2", customerOrderEntity.getGoldOrderNumber());
int modification=query.executeUpdate();
}
catch(PersistenceException ex) {
otLogger.debug("OrderDaoImpl.exception occurred "+ex);
throw new TechnicalException(Constants.ERROR_HIBERNATE_EXCEPTION, ex);
}
}

I think your property is something like
private boolean msgFromUserFlag=false;
and the getters and setters were produced by eclipse itself, which will generate them like
public boolean isMsgFromUserFlag() {
return msgFromUserFlag;
}
public void setMsgFromUserFlag(boolean msgFromUserFlag) {
this.msgFromUserFlag = msgFromUserFlag;
}
You can try changing the getter to getMsgFromUserFlag(), because wrong getter methods sometimes causes Mapping Exception while publishing the project.

Related

Why is just this one field of a Hibernate controlled object/entity not being created or updated?

I have an object "Chemical" that is updated according to entries in an HTML page. The data is returned to the Java code correctly, yet this one field is not updating or being created in the database. The chemical entity is defined as follows:
#Entity
#NamedQuery(name="Chemical.findAll", query="SELECT c FROM Chemical c")
public class Chemical implements Serializable {
#Id
#Column(name="chemical_id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int chemicalId;
...
private string formula; <--- THE FIELD THAT WILL NOT UPDATE/BE CREATED
....
public void setFormula(String formula) {
this.formula = formula;
}
public String getFormula() {
return this.formula;
}
.....
The Java code that actually saves/updates the database:
public void saveOrUpdate(final T data) throws CPDPersistenceException {
final EntityManager em = getEntityManager();
try {
final EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.merge(data);
transaction.commit();
} catch (final PersistenceException e) {
throw new PersistenceException(e);
}
}
After the code is executed, other fields have changed in the database if changes have been made. However, "formula" is not changed and remains a NULL field. Can anybody see why?
There is I think a difference between UPDATE and CREATE.
Try to replace em.merge(data) with em.persist(data)
Does it save the content the first time you create a new row with persist ?
What is the length of your string definition in the database ?
Check the database logs whenever the HQL is run from your code, do the log complain at one point during the persist ?
It might be necessary to first test if the row exists before you can run a merge.

Spring-JPA-data save entity UNIQUE INDEX(two columns ,not pk ) violated cann't throw Exception

my java code like this:
public class Monitorlog{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;//pk
String sn; // unique constraints(sn,checkpoint)
String checkpoint;
}
public interface MonitorlogDao extends JpaRepository<Monitorlog, Integer>{}
#Service
public class MonitorlogService{
#Autowired
MonitorlogDao monitorlogDao;
public MonitorlogDao getMonitorlog(){
return monitorlogDao;
}
}
The test is like this:
public void testMonitorlogSerivce(){
Monitorlog m = new Monitorlog();
m.setSn("aa");
m.setCheckpoint("bb");
monitorlogService.getMonitorlogDao().save(m);
m = new Monitorlog();
m.setSn("aa");
m.setCheckpoint("bb");
// SQL insert failed here
try{
monitorlogService.getMonitorlogDao().save(m);
}catch(Exception e){
log("",e);
}
}
The secode save(m) is failed , it would like throw a exception, but not.
the m.getId() is 0, but no exception catched, why?
I use sprint boot ver 2.0.0M.
UNIQUE INDEX
CREATE UNIQUE INDEX [IND_IDNO_POSITIONKIND_CHECKPOINT_1] ON
[dbo].[MONITORLOG] ([CHECKPOINT] DESC, [SN] ASC)
WITH (IGNORE_DUP_KEY = ON)
Your provided data on second save violates the PK and/or UK rules of DB.
Always you have to give valid data which will comply the PK and/or UK(unique key) rules to persist in DB for your code.

HIbernate not fetching value where the field is null in database record

I am using the below hibernate code to fetch the data from database.
SessionFactory factory = null;
Session session = null;
try {
factory = getSessionFactory();
session = factory.openSession();
final Criteria criteria = session
.createCriteria(CrfEmailDataBean.class);
criteria.add(Restrictions.eq(CAMPN_NBR, campNbr));
returnList = criteria.list();
} catch (Exception e) {
logger.error(e.getMessage());
throw new DAOException(e);
} finally {
DBUtil.close(factory, session);
}
if (logger.isInfoEnabled()) {
logger.info(LOG_METHOD_EXIT);
}
return returnList;
}
Inside CrfEmailDataBean class, I have declared a private String crfEmailTypeCd; field which is null in database. Because of null, it is not setting the record in return list. If I go and enter a value inside the field in database, it fetches.
I tried running the query directly on sql database, the query formed is correct and fetches all the data.
Why it is not fetching that record? and how can I resolve this?
when you use type properties primitive same, need set the default value, same zero (0) or (a) ( ..)
private int number;
private int value;
private char option;
if hibernate database ready null, when converters of the Hibernate generator a error
solution for this never user primitive type
Or define de default value for properties
Each other possibility your date not null, this value white
white is different of the null
make a test put conditions Restrictions.isNotNull.
make other test put conditions Restrictions.isNull.
other test make a method receive int, call send one Integer null
first item
private Integer number;
private Integer value;
private Character option;
last item test
public class Test{
public static void setInt(int value){
System.out.println(value);
}
public static void main(String[] args)
{
Integer testValue=null;
Test.setInt(testValue);
} }

Boolean value not getting mapped properly in Hibernate with MySQL

I am trying to map the result of an exists query (which returns TRUE/FALSE) from a MySQL database to a POJO via resultSetTransformer. I would hope the result of this exists query can get mapped to a boolean but it does not and throws the below error:
org.hibernate.PropertyAccessException: IllegalArgumentException
occurred while calling setter of TestBean.value
The cause of this exception is shown as:
java.lang.IllegalArgumentException: argument type mismatch
My sample class:
public class TestHibernate {
private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
public static void main(String[] args) throws ParseException {
try {
Query query = sessionFactory.openSession().createSQLQuery(
"SELECT " +
"EXISTS (SELECT * FROM A WHERE id = 3) AS value"
);
query.setResultTransformer(Transformers.aliasToBean(TestBean.class));
List<TestBean> beanList = (List<TestBean>) query.list();
} catch (Exception e) {
System.out.println(e);
}
}
}
The POJO:
public class TestBean {
private boolean value;
public boolean isValue() {
return value;
}
public void setValue(boolean value) {
this.value = value;
}
}
Am I missing something or is it a bug with Hibernate or MySQL JDBC Driver?
Hibernate version: 3.2.6GA
MySQL JDBC Driver: mysql-connector-java-5.1.2
Hibernate has a built-in "yes_no" type that would do what you want. It maps to a CHAR(1) column in the database.
Basic mapping:
<property name="some_flag" type="yes_no"/>
Annotation mapping (Hibernate extensions):
#Type(type="yes_no")
public boolean getFlag();
Your problem may be caused by the case mapping of the selected column, q.v. my solution below. I also parametrized your WHERE clause to avoid SQL injection.
Query query = session.createSQLQuery("select exists(select * from A where id = :id) as value");
.setParameter("id", "3");
.addScalar("value")
.setResultTransformer( Transformers.aliasToBean(TestBean.class))
List result = query.list();
TestBean theBean = (TestBean)result.get(0);
The transform of the result query can be explicitly set each parameter to the corresponding model datatype using hibernate addScalar() method. Please find the solution below.
Query query = sessionFactory.openSession().createSQLQuery(""+
"select " +
" exists(select * from A where id = 3) as value"
).addScalar("value", BooleanType.INSTANCE);
This will resolve to set to the Boolean value.
I know this is old answer, I tried to resolve this coz answer from here not worked for me.
with Addition to Answer from #anil bk, I overloaded a setter method accepting String as argument. Now It worked as expected.
public void setPriority(String priority) {
this.priority = "true".equals(priority);
}
Here is my answer

can i have a method in entity class without Mapping to the database

I am using Hibernate to map with MySQL
I have an entity class in which I have the methods mapped with columns in MySQL
The question is, if its possible that I do not map some of the method in that class with any column in SQL, as if i try not to map one of my method in entity class, it gives exception.
Here is the code snippet , what i am trying
#Column(name="skills")
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
#Transient
public int getRowCount() {
return rowCount;
}
public void setRowCount(int count) {
this.rowCount = count;
}
I have used #transiet , but after this if i set some value in setRowCunt and then tries to get that same value with getRowCount it gives null value , anyone have some idea
thanks
You are correct with the #Transient annotation. Perhaps you are setting the rowCount value in one object, than fetch it from db and try to get the value from it? - it would obviously fail because the field is not persisted and you're dealing with new instance of that object.
Perhaps You could provide broader context - what are the steps between setting a value and getting null?

Categories