org.hibernate.MappingException: Unknown entity when trying to save POJO - exception

I get the below error when I invoke the method to save an entity to the database.
ERROR: org.aggu.sramam.exceptions.SramamException - Exception thrown:
org.hibernate.MappingException: Unknown entity: org.aggu.sramam.pojo.SramaSangham
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443
The POJO object is there in the package, and I also have the below entry in my hibernate-cfg.xml file
<hibernate-configuration>
<!-- List out the entities (i.e POJO linked to DB table) here -->
<session-factory>
<mapping class="org.aggu.sramam.pojo.SramaSangham" />
</session-factory>
</hibernate-configuration>
Below is the entry in the servlet-config.xml file, which gives the code base links
<!-- The below is the base package for all Sramam apps -->
<context:component-scan base-package="org.aggu.sramam" />
What have I missed here? I have added the #Entity, #Table, #Id tags etc. in the POJO object. There is an Unqiue ID column (Primary key), but I have not written any explicit code to generate the ID automatically. Would that be a problem?

Okay. Figured this out myself. The issue was that in my servlet-context.xml file, I had NOT given a reference/link to the hibernate.cfg.xml. Once this was given, the error got resolved and records started getting inserted.
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
</beans:props>
</beans:property>
**<!- This line did the trick -->
<beans:property name="configLocation">
<beans:value>WEB-INF/classes/hibernate.cfg.xml</beans:value>
</beans:property>**
</beans:bean>

Related

Checkstyle CustomImportOrder more than 3 definable groups?

My company's Java import order standard would require more than the three definable groups that I see in checkstle, which are STANDARD_JAVA_PACKAGE, THIRD_PARTY_PACKAGE, and SPECIAL_IMPORTS. My question has two parts:
Is there a way to define more custom regular expressions, or use regexes directly in the VALUE for customImportOrderRules?
Can I do this at all, since com.our_company is supposed to come after all the other com. imports.
The import rules are approximately
Static imports
java.*
javax.*
com.* EXCEPT our company
nthing.*
org.*
pthing.*
com.mycompany.*
anything else
Since we also enforce blank lines between groups, I can't combine 5, 6, and 7 into one and depend on sort order to keep things clean. Worst case is that we already have this defined in Intellij and just have to remember to auto-order imports every time.
Answering your questions:
According to this ticket it looks like there is no way to achieve what you need using just CustomImportOrder. Instead you should use ImportOrder, complete example below.
It is possible using ImportOrder
This should work for your case:
<module name="ImportOrder">
<property name="option" value="top"/>
<property name="groups" value="/^java\./,javax,/^com\.(?!mycompany)/,nthing.org,pthing,com.mycompany"/>
<property name="ordered" value="true"/>
<property name="separated" value="true"/>
<property name="separatedStaticGroups" value="true"/>
<property name="sortStaticImportsAlphabetically" value="true"/>
</module>
Small clarification. Inside the groups property there are two groups /^com\.(?!mycompany)/ and com.mycompany, first one is the regexp that use negative look-ahead, second one is just common prefix string for the import.

REP-56132 Access is denied to the report definition file

I have been researching this problem for a couple weeks now and at a dead end.
Running 12c form and reports, Linux OEL 6, WebLogic 12c. Also, this is a 6i to 12c migration of all objects. This fails when sending the report directly across in the URL and with web.show_document.
Have added the COMPONENT_CONFIG_PATH, added the suggested changes to rwserver.conf and the rwservlet.properties, all folders and objects are wide open at 0777. I've tried a number of different users with various privileges but all have resulted in the same error. I have tried with RUN_REPORT_OBJECT and that also results in an error of FRM-41219. Here is the rwserver.confg:
<?xml version="1.0" encoding="UTF-8"?>
<server xmlns="http://xmlns.oracle.com/reports/server" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<cache class="oracle.reports.cache.RWCache">
<property name="cacheSize" value="50"/>
</cache>
<engine class="oracle.reports.engine.EngineImpl" engLife="1" id="rwEng" maxEngine="1" minEngine="1" maxIdle="3" callbackTime="90000">
<property name="sourceDir" value="/app01/bcis/forms"/>
<property name="tempDir" value="/app01/oracle/tmp"/>
<property name="keepConnection" value="yes"/>
</engine>
<engine class="oracle.reports.urlengine.URLEngineImpl" engLife="50" id="rwURLEng" maxEngine="1" minEngine="0"/>
<!--
<destination class="oracle.reports.server.DesFile" destype="file"/>
<destination class="oracle.reports.server.DesCache" destype="cache"/>
<destination class="oracle.reports.server.DesPrint" destype="printer"/>
-->
<destination class="oracle.reports.plugin.destination.ftp.DesFTP" destype="ftp"/>
<destination class="oracle.reports.plugin.destination.webdav.DesWebDAV" destype="WebDav"/>
<!--job engineId="rwEng" jobType="report" securityId="Empty"/-->
<!--job engineId="rwURLEng" jobType="rwurl" securityId="Empty"/-->
<notification class="oracle.reports.server.MailNotify" id="mailNotify">
<property name="succnotefile" value="succnote.txt"/>
<property name="failnotefile" value="failnote.txt"/>
</notification>
<jobRepository>
<property name="dbuser" value="rwadmin"/>
<property name="dbpassword" value="csf:reports:repo"/>
<property name="dbconn" value="dcis2d01.mlgw.org:1522:CISDB12"/>
</jobRepository>
<connection idleTimeOut="30" maxConnect="250"/>
<queue maxQueueSize="1000"/>
<folderAccess>
<read>/app01/bcis/forms:/app01/bcis/reports:/app01/bcis/dev/exe:/app01/bcis/exe:/app01/oracle/tmp</read>
<write>/app01/bcis/forms:/app01/bcis/reports:/app01/bcis/dev/exe:/app01/bcis/exe:/app01/oracle/tmp</write>
<defaultWriteFolder>/app01/bcis/forms</defaultWriteFolder>
</folderAccess>
<identifier encrypted="yes">QgZSFEalKUbL0t/KwwqSEg0=</identifier>
<proxyInfo>
<proxyServers>
<proxyServer name="$$Self.proxyHost$$" port="$$Self.proxyPort$$" protocol="all"/>
</proxyServers>
<bypassProxy>
<domain>$$Self.proxyByPass$$</domain>
</bypassProxy>
</proxyInfo>
<pluginParam value="%MAILSERVER_NAME%" name="mailServer"/>
</server>
The naming service:
<namingService name="Cos" host="10.211.212.164" port="14021"/>
I have checked the spelling of all paths, so they are right and they do run under rwrun and I can bring them up in rwbuilder.
If there is anything else that would be helpful, please let me know.
Any suggestions at this point will be helpful and I would appreciate as many quick responses as possible.
Have you added the report as an object in the calling form? (Similar to adding a new canvas or new datablock)
The find_report_object call should be passed the name of the report object as it was added to the form. The FRM-41219 makes me think you haven't added the report object. This did not need to be done in 6i.
Have you tried to verify that the reports are generated? You could try trigger generation of a report directly from a curl command on the reports server. I use something like the below URL to verify that the reportsserver is running:
http://reportsserver:port/reports/rwservlet?userid=user/password#tnsname&destype=cache&report=reportnam.rdf&desformat=PDF&argument1=123&argument2=456

Use Hibernate Annotation on databean: Cannot add constraint to MySQL table

I try to add constraints to MySQL table via databeans using hibernate annotation:
package databean;
import javax.persistence.*;
#Entity
#Table(name = "ADMIN",
uniqueConstraints = {
#UniqueConstraint(columnNames = "userName"),
#UniqueConstraint(columnNames = "email")
})
public class AdminBean {
// Private fields
#Id #GeneratedValue
#Column(name = "adminId")
private int adminId; // PK
#Column(name = "userName")
private String userName;
I also have 2 xml files for mapping: hibernate.cfg.xml and Admin.hbm.xml
1)
mapping resource="hibernate/Admin.hbm.xml"/
2)
<hibernate-mapping>
<class name="databean.AdminBean" table="ADMIN">
<meta attribute="class-description">
This class contains the admin detail.
</meta>
<id name="adminId" type="int" column="adminId">
<generator class="native"/>
</id>
<property name="userName" column="userName" type="string"/>
<property name="firstName" column="firstName" type="string"/>
<property name="lastName" column="lastName" type="string"/>
<property name="email" column="email" type="string"/>
<property name="phone" column="phone" type="string"/>
<property name="password" column="password" type="string"/>
<property name="city" column="city" type="string"/>
<property name="zipCode" column="zipCode" type="string"/>
</class>
</hibernate-mapping>
According to what I've found online:
"So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations is the newest way to define mappings without a use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development." (http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm)
If I comment out the xml files mapping, I will get the exception of "Unknown entity: databean.AdminBean". Cannot even find the databean now.
Question:
1) Shouldn't the databean with hibernate annotations work even if there is no mapping in xml file? (So it does not even work now...)
2) If there is no hibernate annotation with databean, should I add constraints directly into the xml mapping file?
3) What is the best way to add constraints to MySQL tables? Since they are all automatically created when I run the application, it doesn't seem to make much sense to add constraints by building tables manually in mySQL first?
4) Is it really necessary to add constraints to both databean and (maybe) xml files?
Update:
Even when I try to set the property in xml file, mySQL database seems not to be able to "catch the constraints" and tables can still add duplicates items.
Now I doubt it might not be a problem with the way I add those constraints, but more like a "disconnection" with mySQL table and my code...though other parts can function pretty well. Anyone has faced similar situations before?
I find the reason: I did not drop the previous table when there is no constraint added when it is first created automatically by my app. Hope no one makes the same mistake. :)

Issue while saving Non-English character

We are working with one application where we need to save data in language Gujarati.
Technologies used in Applcation is listed below.
Spring MVC Version 4.1.6.RELEASE
Hibernate Version 4.3.5.Final
MySQL 6.0.11
My JSP is configured with
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
And
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Hibernate configuration is
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
MySQL URL is
jdbc:mysql://host:port/dbName?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8
Pojo having String field to store that data.
MySQL have VARCHAR datatype to store data with charset=utf8 and Collation=utf8_general_ci
When i tried to save any non-english(Gujrati) character it show some garbage character like àª?à«?àª? for "ગુજ".
Is there any other configuration which i missed here.
I was facing the same problem while inserting "tamil" characters into the database.After surfing a lot I got a better and working solution and it solves my problem.Here I am sharing my solution with you.I hope it will help you to clear your doubts regarding that Non English character.
INSERT INTO
STUDENT(name,address)
VALUES
(N'பெயர்', N'முகவரி');
I am using a sample since you have not provided me any structure of your table and field name.
I am assuming you want ગુજ (GA JA with Vowel sign U)?
I think you somehow specified "latin5". (Yes I see you have UTF-8 everywhere, but "latin5" is the only way I can make things work.)
CONVERT(CONVERT(UNHEX('C3A0C2AAC297C3A0C2ABC281C3A0C2AAC29C')
USING utf8) USING latin5) = 'ગુજ'
Plus you ended up with "double encoding"; I suspect this is what happened:
The client had characters encoded as utf8 (good); and
SET NAMES latin5 was used, but it lied by claiming that the client had latin5 encoding; and
The column in the table declared CHARACTER SET utf8 (good).
If possible, it would be better to start over -- empty the tables, be sure to have SET NAMES utf8 or establish utf8 when connecting from your client to the database. Then repopulate the tables.
If you would rather try to recover the existing data, this might work:
UPDATE ... SET col = CONVERT(BINARY(CONVERT(
CONVERT(UNHEX(col) USING utf8)
USING latin5)) USING utf8);
But you would need to do that for each messed up column in each table.
A partial test of that code is to do
SELECT CONVERT(BINARY(CONVERT(
CONVERT(UNHEX(col) USING utf8)
USING latin5)) USING utf8)
FROM table;
I say "partial test" because looking right may not prove that is right.
After the UPDATE, SELECT HEX(col) get E0AA97E0AB81E0AA9C for ગુજ. Note that most Gujarati hex should be of the form E0AAyy or E0AByy. You might also find 20 for a blank space.
I apologize for not being more certain. I have been tackling Character Set issues for a decade, but this is a new variant.
There might be a couple of things that you could have missed out. I had the same problem with mysql on linux, what I had to do is to edit my.cnf like this:
[client]
default-character-set = utf8
[mysqld]
character-set-server = utf8
For e.g. on Centos this file is location at /etc/my.cnf on Windows (my pc) C:\ProgramData\MySQL\MySQL Server 5.5\my.ini. Please note that ProgramData might be hidden.
Also the other thing if you are using Tomcat is that you have to sepcify UTF-8 for URI encoding. Just edit server.xml and modify your main Connector element:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
URIEncoding="UTF-8"
redirectPort="8443" />
Also make sure you added character encoding filter in your application:
#WebFilter(filterName = "CharacterEncodingFilter", urlPatterns = {"/*"})
public class CharacterEncodingFilter implements Filter {
#Override
public void init(FilterConfig filterConfig)
throws ServletException {
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
request.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html; charset=UTF-8");
filterChain.doFilter(request, servletResponse);
}
#Override
public void destroy() {
}
}
Hope this helps.
Another tip, don't lean only on setting the characterEncoding as a hibernate property <prop key="hibernate.connection.characterEncoding">UTF-8</prop>, make sure you add it explicitely as connection variable on the DB url, so
jdbc:mysql://host:port/dbName?useUnicode=true&characterEncoding=UTF-8&connectionCollation=utf8_general_ci&characterSetResults=utf8
Also, as there is some many layers where an encoding would be lost, you can try to isolate the layer and update to a question. E.g. if its upon storing to DB, or at some point before
Your applicationContext file should be like this:
To make Spring MVC application supports the internationalization, register two beans :
SessionLocaleResolver
Register a “SessionLocaleResolver” bean, named it exactly the same characters “localeResolver“. It resolves the locales by getting the predefined attribute from user’s session.
Note
If you do not register any “localeResolver”, the default AcceptHeaderLocaleResolver will be used, which resolves the locale by checking the accept-language header in the HTTP request.
LocaleChangeInterceptor
Register a “LocaleChangeInterceptor” interceptor and reference it to any handler mapping that need to supports the multiple languages. The “paramName” is the parameter value that’s used to set the locale.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
<!-- Register the bean -->
<bean class="com.common.controller.WelcomeController" />
<!-- Register the welcome.properties -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="welcome" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
The native2ascii is a handy tool build-in in the JDK, which is used to convert a file with ‘non-Latin 1′ or ‘non-Unicode’ characters to ‘Unicode-encoded’ characters.
Native2ascii example
Create a file (source.txt)
Create a file named “source.txt”, put some Chinese characters inside, and save it as “UTF-8″ format.
native2ascii
Use native2ascii command to convert it into Unicode format.
C:>native2ascii -encoding utf8 c:\source.txt c:\output.txt
The native2ascii will read all the characters from “c:\source.txt” and encode it with “utf8″ format, and output all encoded characters to “c:\output.txt”
Read Output
Open the “c:\output.txt”, you will see the all encoded characters, e.g \ufeff\u6768\u6728\u91d1
welcome.properties
welcome.springmvc = \u5feb\u4e50\u5b66\u4e60
Call the above string and store the value in database.
And if you want to display that inside JSP page:
Remember add the line
“<%# page contentType=”text/html;charset=UTF-8″ %>”
on top of the jsp page, else the page may not able to display the UTF-8
(Chinese) characters properly.

Spring transaction issue with tomcat, mysql and eclipselink

I've got lot of confusions after googling for spring transactions with eclipselink, tomcat and mysql. Please consider the following questions and guide me on this topic.
Can i run spring transactions with eclipseLink, tomcat and mysql enviornment? if so how is the config? i have used the following config and i get lock exceptions always.
Persistence.xml:
<persistence-unit name="xxxxService" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>...</class>
<class>...</class>
<class>...</class>
<properties> .... </properties>
</persistence-unit>
Spring-beans.xml:
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="persistenceUnitName" value="xxxxService" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
JAVA class:
#Transactional
public void saveSumthg(Sumthg sumthg) throws Exception{
someDAO.saveSumthg(sumthg);
}
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public List<Sumthg> findActiveSumthgs(String username) {
List<Sumthg> sumthgs = someDAO.findActiveSumthgs(username);
return sumthgs ;
}
Am i doing anything wrong here? I'm not sure whether spring transaction handling works correctly with tomcat since i'm not using JTA transactions.
With EclipseLInk and mysql, Id generation strategy goes with Sequence table and in the table only one row is updated for all transactions. I suspect that this causes lock issues. Am i correct? If so, how can i avoid this?
ID generation config in a Domain class is like this:
#Id
#Column(name = "some_id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
In mysql schema, a new table named SEQUENCE is created and a value is stored in it. Each time when a row is inserted, the id is taken from here i think. Since the same value is read and updated, i suspect that this can cause locking issues.
If i'm correct, how can i avoid this issue??
Looking forward for your answers.
Thanks.
got an update - i can see the following is logs:
Internal Exception: java.sql.SQLException: Lock wait timeout exceeded; try restarting
transaction
Error Code: 1205
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [50, SEQ_GEN]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT =
SEQ_COUNT + ? WHERE SEQ_NAME = ?")]
So it is clear that this is happening because the same value in SEQUENCE table is being modified by several threads. What is the best ID generation strategy i can use in this context??
The problem is that you are using the worst concurrent ID GENERATION solution (TABLE_SECUENCE).
In this case the best solution is to use the SEQUENCE GENERATION.
The sequencers handle much better the concurrency.
I can't see how you would get lock exceptions always. Are you running multiple threads/clients? Try setting logging on finest to see what is going on.
EclipseLink will normally allocate sequence ids outside of the transaction, so would normally not have any locking conflicts. You can also enable a sequence connection pool in EclipseLink that will always use a seperate connection for allocating ids to avoid any locking conflicts.