I am trying to store gujarati in postgreSQL database using Java Spring Hibernate Project But it is storing something like this
મà«àª¦à«àª¨àª¾ àªàª¯-પરાàªàª¯ પાàªàª³ ઠવà«àª¯àªà«àª¤àª¿àª¨à«àª àªà«àªà«àª
instead of
મોદીના જય-પરાજય પાછળ આ વ્યક્તિનું ભેજું
In my database encoding is UTF-8, if I copy paste directly in postgreSQL it is storing properly but from html form in web application it is not storing properly.
Following is my hibernate.hbm.cfg file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
org.postgresql.Driver
</property>
<property name="connection.url">
jdbc:postgresql://192.168.6.51:5432/JayHind?autoReconnect=true&useUnicode=true&createDatabaseIfNotExist=true&characterEncoding=utf-8
</property>
<property name="connection.username">postgres</property>
<property name="connection.password">pshiv</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<mapping class="com.models.Role" />
<mapping class="com.models.UserAttempts" />
<mapping class="com.models.UserLogin" />
<mapping class="com.models.UserRole" />
<mapping class="com.models.Program" />
<mapping class="com.models.NationalProgram" />
<mapping class="com.models.StateProgram" />
<mapping class="com.models.OtherProgram" />
<mapping class="com.models.Video" />
<mapping class="com.models.Contact" />
<mapping class="com.models.Heading" />
</session-factory>
</hibernate-configuration>
I have also used
% # page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" % >
in jsp pages this make gujarati display properly but in form submission there is still problem.
In model class
package com.models;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import com.sun.istack.internal.NotNull;
#Entity
#Table(name = "tbl_heading_info", uniqueConstraints = {
#UniqueConstraint(columnNames = "id")})
public class Heading {
private int id;
#NotNull
#NotBlank
private String message;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "message", nullable = false)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
/*byte ptext[] = null;
try {
ptext = message.getBytes("ISO_8859_1");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String value = new String(ptext, "UTF-8");
this.message=value;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */
}
}
I have also put filter in web.xml
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
Expected Output
Current Output
I had to face this the last week, try this.
Use 'definitivo' has the textBox.getText() and convert to UTF-8
byte ptext[] = definitivo.getBytes("ISO_8859_1");
String value = new String(ptext, "UTF-8");
Related
Getting a java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist when trying to insert a new object into my Oracle table. The table does have a sequence that automatically increments upon each entry.
I've been stuck on this for a few hours and after following similar answers to this question and other articles, I'm still stuck.
My class:
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
#Entity
#Table(name = "MY_SCHEMA.MY_TABLE")
#Component
public class SomeClass {
#Id
#SequenceGenerator(name = "MY_SEQ", sequenceName = "MY_SEQ", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQ")
#Column(name = "MY_ID")
private Integer myId;
#Column(name = "MY_TS")
private Timestamp ts;
#Column(name = "MY_PARAM")
private String myParameters;
#Column(name = "ANOTHER_TS")
private Timestamp anotherTimestamp;
// empty constructor and getters/setters
}
DAO for the class:
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Component;
import mypackage.mysubpackage.SomeClass;
#Component
public class SomeClassDAO {
private Session currentSession;
private Transaction currentTransaction;
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(SomeClass.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
return factory;
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionWithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionWithTransaction() {
currentTransaction.commit();
currentSession.close();
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
// post
public void insertNew() {
SomeClass obj = new SomeClass();
obj.setParameters("abc");
getCurrentSession().save(obj);
}
}
DDL snippet for the sequence:
begin
if inserting then
if :NEW."MY_ID" is null then
select MY_SEQ.nextval into :NEW."MY_ID" from dual;
end if;
end if;
end;
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-5.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:oracle:thin:#servername.company.net:123:ABC</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.username">user</property>
<property name="connection.password">pass</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
mvc-dispatchet-servlet.xml snippet:
<context:component-scan base-package="mypackage.mysubpackage"></context:component-scan>
<mvc:annotation-driven/>
<context:annotation-config/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#servername.company.net:123:ABC"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="mypackage.mysubpackage"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManger"/>
begin
if inserting then
if :NEW."MY_ID" is null then
select MY_SEQ.nextval into :NEW."MY_ID" from dual;
end if;
end if;
end;
This looks to me like part of oracle trigger rather than actual oracle Sequence. Check if sequence is actually present with name "MY_SEQ" in your schema.
If you have the sequence in place with the current JPA annotations on your id column, you do not require the trigger. JPA itself can get the sequence next value without the trigger.
If you still want to continue using the trigger read here.
I am getting this error because of this my application is not able to create a bean for sessionFactory and bean for transactionManager.
nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.entity.Candidate"/>
Here I am sharing my code hope that gives better clarity.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false">
<servlet>
<servlet-name>conceptedge</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/conceptedge-persistence.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>conceptedge</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
sessionFactory bean:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/interview"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
in Dao layer, I am accessing the session as mentioned:
#Autowired
SessionFactory sessionFactory;
#Override
public List<Candidate> getCandidatesList() {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Candidate.class);
return criteria.list();
}
entity class
package com.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
#Entity
public class Candidate {
private int number;
private String name;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#GenericGenerator(name = "system-uuid", strategy = "uuid")
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
servlet.xml:
<context:component-scan base-package="com" >
<context:include-filter type="regex" expression="com.*"/>
</context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
You have to annotate your class with #Entity and #Table when using
<mapping class="com.entity.Candidate"/>
or else, you need to use sth like
<mapping resource="com/entity/Candidate.hbm.xml" />
and add the equivalent xml mapping file for your entity class.
also dont forget to initialize your sessionFactory with AnnationConfiguration class
new AnnotationConfiguration().configure().buildSessionFactory();
I am using Hibernate project in my eclipse with oracle database and java application.
after added new class(exist in my database) to my Hibernate project, and run my java project.it's loaded successfully also allow to add data from java project to hibernate table but at add these data to database i got this error
Unknown entity: com.se.automation.db.client.mapping.DocumentWRONGMODDATESTATUS
here is my code to add data to my database.
note ( I opened the session and i test it with another class exist in the same Hibernate project with the same structure to this class "Hibernate Project" )
DocumentWRONGMODDATESTATUS docstatus = new DocumentWRONGMODDATESTATUS();
docstatus.setOriginalDocId(doc.getPdf().getId());
at this moment every thing fine , but below line give the error(test it in debugging mode)
addDocumentWrongModDateStatus(docstatus ,Session );
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Enable Hibernate's automatic session context management -->
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="connection.autoReconnect">true</property>
<!-- <property name="show_sql">true</property> -->
<property name="show_sql">true</property>
<property name="format_sql">false</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<!-- auto commit -->
<property name="connection.autocommit">true</property>
<!-- configuration pool via c3p0 -->
<property name="c3p0.idleConnectionTestPeriod">1000</property>
<property name="c3p0.initialPoolSize">1</property>
<property name="c3p0.maxPoolSize">1</property>
<property name="c3p0.maxIdleTime">1</property>
<property name="c3p0.maxStatements">3</property>
<property name="c3p0.minPoolSize">1</property>
<mapping resource="com/se/automation/db/client/mapping/DocumentWRONGMODDATESTATUS.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareChangedFet.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareCode.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareComment.hbm.xml" />
<mapping
resource="com/se/automation/db/client/mapping/DocumentCompareMethod.hbm.xml" />
</session-factory>
</hibernate-configuration>
DocumentWRONGMODDATESTATUS.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.se.automation.db.client.mapping.DocumentWRONGMODDATESTATUS"
table="DOCUMENTWRONGMODDATESTATUS">
<id column="ID" length="33" name="id" type="long">
<generator class="assigned" />
</id>
<property name="Status" type="java.lang.String">
<column name="STATUS" />
</property>
<property name="OriginalDocId" type="java.lang.Long">
<column name="ORIGINALDOCID" />
</property>
<property name="RevDocId" type="java.lang.Long">
<column name="REVDOCID" />
</property>
</class>
</hibernate-mapping>
DocumentWRONGMODDATESTATUS.java
package com.se.automation.db.client.mapping;
import java.io.Serializable;
public class DocumentWRONGMODDATESTATUS implements Serializable
{
private static final long serialVersionUID = 1L;
private Long id;
private String Status;
private Long OriginalDocId;
private Long RevDocId;
public Long getOriginalDocId()
{
return OriginalDocId;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getStatus()
{
return Status;
}
public void setStatus(String status)
{
Status = status;
}
public void setOriginalDocId(Long originalDocId)
{
OriginalDocId = originalDocId;
}
public Long getRevDocId()
{
return RevDocId;
}
public void setRevDocId(Long revDocId)
{
RevDocId = revDocId;
}
{
}
}
Trying to learn Hibernate, i am trying to learn how to execute NamedQuries but evertime i am getting Exception in thread "main" org.hibernate.MappingException: Named query not known.Please help me out here
Error (only the message, not showing complete stack)
Exception in thread "main" org.hibernate.MappingException: Named query not known: hibernate_tut_emp.Employee.FindCountOfNames
at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1372)
at hibernate_tut_emp.MyOps.main(MyOps.java:20)
Employee.java
package hibernate_tut_emp;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
#Entity
#Table(name="Hib1")
#NamedQueries({
#NamedQuery(name="GetDetailsByName" , query="select * from hib1 h where h.name=:name"),
#NamedQuery(name="FindCountOfNames", query="select count(1) as cnt from hib1 h where h.name=:name")
})
public class Employee {
private int id;
private String name;
#Id
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String empName) {
this.name = empName;
}
}
MyOps.java
package hibernate_tut_emp;
import java.util.Scanner;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class MyOps {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a name : ");
String name = scnr.next();
SessionFactory ses = HibernateUtil.getSessionFactory();
Session session = ses.openSession();
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
query.setString("name", name);
int count = ((Integer)query.iterate().next()).intValue();
System.out.println("count : "+count);
}
}
employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_tut_emp.Employee" table="hib1">
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">mayank</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="hibernate_tut_emp.Employee" />
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I googled out everything possible but i think i am overlooking some basic stuff.Any indication in right direction is appreciated! :)
One thing i considered is that if i have defined in class file NamedQueries, i do not need to mention it in xml file.Please correct me if i am wrong!
There are several issues here:
Your named queries should use entities not tables. If you want native queries you should use NamedNativeQuery instead.
You don't need to supply the entity name when fetching the query.
Change this:
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
to:
Query query = session.getNamedQuery("FindCountOfNames");
Hi I am trying to use anotation to do named query. The line that caused Named query not known is:
HibernateUtil.openSession().getNamedQuery(
"getWorkById")
Here is all the code about my named query. Actually I also tried to do so in mapping files, but I also got error and don't know what error is because it just reported internal failure. Any help about how to fix the error? Also, what is a better practice to do named query? Thanks!
WorkModel:
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#NamedQueries({
#NamedQuery(name = "getWorkById", query = "from myday.work w where w.id = :id")
})
#Entity
#Table(name = "myday.work")
public class WorkModel {
private Long id;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
WorkModel hbm xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="model.WorkModel" table="myday.work">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="increment" />
</id>
</class>
</hibernate-mapping>
hibernate cfg xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://XXX:3306</property>
// username, pwd setting...
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<mapping class="model.WorkModel"/>
<mapping resource="model/WorkModel.hbm.xml"/>
</session-factory>
</hibernate-configuration>