i want to add person in database using ibatis in j2EE application.
I have a table person in mySQL, servlet,SqlMapConfix.xml,Person.xml and Person.java.
i did many tests but i had the same error.
java.lang.RuntimeException: Error occurred. Cause: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource config/Person.xml
here the code :
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="Controller" >
<input type="text" name="nom">
<input type="text" name="pren">
<input type="submit" value="ok">
</form>
</body>
servlet: Controller.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String a = request.getParameter("nom");
String b = request.getParameter("pren");
try{
Reader rd;
rd = Resources.getResourceAsReader("config/SqlMapConfig.xml");
SqlMapClient smc;
smc = SqlMapClientBuilder.buildSqlMapClient(rd);
out.println("Going to insert record.....");
Person em = new Person(a, b);
smc.insert("Person.insert", em);
out.println("Record Inserted Successfully ");
}catch(SQLException e)
{e.printStackTrace();}
}
Person.java
package controleur;
public class Person {
String nom,prenom;
public Person(String nom, String prenom) {
this.nom = nom;
this.prenom = prenom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
}
Person.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">
<insert id="insert" parameterClass="controleur.Person" >
insert into person(nom, pren)values(#nom#, #prenom#)
</insert>
</sqlMap>
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<settings useStatementNamespaces="true"></settings>
<transactionManager type="JDBC">
<dataSource type="simple">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/parc"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</dataSource>
</transactionManager>
<sqlMap resource="config/Person.xml "/>
i used two package: package config contains *.xml files and package controleur contains the servlet and the java class.
thanks
Moved the xml file to where the Pojo was located, in your example move it under controleur package where Person.java is located then update the sqlMap as follows.
<sqlMap resource="controleur/Person.xml" />
Related
I have taken reference from ->
https://www.quora.com/How-can-I-make-my-first-JSP-page-using-MySQL-database
At first jsp file is opening , i can input data but after clicking at submit , it gives error as in the image provided.
i m using tomcat v7.0 and it works correct for all other projects !
code->
Login.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
Register.java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}else{
out.println("Invalid User");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
You forgot to add web.xml as in tutorial the servlet
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
I have been trying to insert a Student record in mysql database, using spring 3 & mybatis3, but i am constantly getting following exception.
com.ibatis.common.jdbc.exception.NestedSQLException:
ERROR [stderr] (http-localhost/127.0.0.1:8080-4) --- The error occurred in /config/StudentMapper.xml.
ERROR [stderr] (http-localhost/127.0.0.1:8080-4) --- The error occurred while applying a parameter map.
ERROR [stderr] (http-localhost/127.0.0.1:8080-4) --- Check the insertStudent-InlineParameterMap.
ERROR [stderr] (http-localhost/127.0.0.1:8080-4) --- Check the statement (update failed).
ERROR [stderr] (http-localhost/127.0.0.1:8080-4) --- Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'lastName)' at line 1
Please Help me resolve this exception.
sqlMapConfig.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<properties resource="/config/SqlMapConfigExample.properties"/>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
useStatementNamespaces="false" />
<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}" />
<property name="JDBC.ConnectionURL" value="${url}" />
<property name="JDBC.Username" value="${username}" />
<property name="JDBC.Password" value="${password}" />
<property name="JDBC.DefaultAutoCommit" value="true"/>
</dataSource>
</transactionManager>
<sqlMap resource="/config/StudentMapper.xml" />
</sqlMapConfig>
My StudentMapper.xml-
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="com.fulcrum.mappers.StudentMapper">
<resultMap id="result" class="com.fulcrum.model.Student">
<result property="id" column="id" />
<result property="firstName" column="firstName" />
<result property="lastName" column="lastName" />
</resultMap>
<insert id="insertStudent" parameterClass="com.fulcrum.model.Student">
<![CDATA[
INSERT INTO student (firstName, lastName) VALUES (#firstName,#lastName);
]]>
<selectKey keyProperty="id" >
SELECT LAST_INSERT_ID() AS id
</selectKey>
</insert>
</sqlMap>
My insertStudentCode in daoimpl-
public void insertStudent(Student student) {
System.out.println("UserDaoImpl insertStudent()");
System.out.println("Student Name::" +student.getFirstName()+" "+student.getLastName());
/*New*/
String resource = "/config/SqlMapConfig.xml";
Reader reader;
try {
reader = Resources.getResourceAsReader (resource);
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
System.out.println("SqlMap::::" +sqlMap);
// sqlMap.startTransaction();
sqlMap.insert("insertStudent", student);
// sqlMap.commitTransaction();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My Student Class Code-
package com.fulcrum.model;
public class Student {
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I looked through some mybatis samples -
Shouldn't mybatis parameters be wrapped as - (#{id}, #{username}, #{password})
https://mybatis.github.io/mybatis-3/sqlmap-xml.html
Looks like the root cause of ur error from your stack trace is - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'lastName)' at line 1
i am trying to create a webpage that has the file upload feature.
FileUpload.jsp
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>file upload Page</title>
</head>
<body bgColor="lightBlue">
<s:form action="fileUpload" method="post" enctype="multipart/form-data" >
<s:file name="userTmp" label="File" />
<br/>
<s:submit value="uploadFile"/>
</s:form>
</body>
</html>
Struts.xml
<package name="upload" namespace="/FileUpload" extends="struts-default">
<action name="fileUpload" class="FileUploadAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
</package>
FileUploadAction.java
public class FileUploadAction extends ActionSupport{
private File userTmp;
private String userTmpContentType;
private String userTmpFileName;
Connection conn = null;
public String execute() throws Exception
{
String result = ERROR;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn= DriverManager.getConnection(".....");
System.out.println("DATABASE CONNECTED");
String sql = "insert into Evidence(Filename, FileType, FileContent,DateSubmitted) values(?, ?, ?, now())";
PreparedStatement pstmt = conn.prepareStatement(sql);
FileInputStream fis = new FileInputStream(userTmp);
pstmt.setString(1, userTmpFileName);
pstmt.setString(2, userTmpContentType);
pstmt.setBinaryStream(3, fis, (int)userTmp.length());
pstmt.executeUpdate();
pstmt.close();
fis.close();
result = SUCCESS;
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
conn.close();
}
return result;
}
public File getUserTmp() {
return userTmp;
}
public void setUserTmp(File userTmp) {
this.userTmp = userTmp;
}
public String getUserTmpContentType() {
return userTmpContentType;
}
public void setUserTmpContentType(String userTmpContentType) {
this.userTmpContentType = userTmpContentType;
}
public String getUserTmpFileName() {
return userTmpFileName;
}
public void setUserTmpFileName(String userTmpFileName) {
this.userTmpFileName = userTmpFileName;
}
}
This is working fine when i am running it on my local tomcat server.
But when I deployed it on a different tomcat server it is giving this error:
No result defined for action FileUploadAction and result input
I tried not doing any thing in the execute method of the FileUploadAction class and just returning the SUCCESS. But it throwed the same error.
After some code debuggin i found this is because of the enctype="multipart/form-data". I modified the FileUpload.jsp page with different enctype and deleted the <s:file> tag in jsp page and it didn't give any error.
Seems weird why it is working on my local tomcat server but not on a different one.
Should I change anything in the tomcat server to get the encype="multipart/form-data" working...
I manage to solve this problem getting hint from post stackoverflow post about GWT. The post tells that as JDBC shouldn'e be on client side, rather on server side.
I am trying to make a simple web application that adds a user to database using GWT RPC with Hibernate, MySql & eclipse IDE. I have already a simple version of hibernate program running & now I am trying to do same using GWT RPC.
Though probably there are certain different practices when using hibernate with RPC. Firstly I had to put jars/libs to war/web.inf/lib add before adding them to classpath, while I made a simple folder in src, put all jars/libraries to that & then added to classpath for simple hibernate app. It continues, compiler then raised error about unavailability of cfg.xml & mapping files which were in the hibernate files package(that contain pojo files). I moved them to src folder & error gone. But now error is about session creation. This time moving Util file to src did not work.
This is directory structure of my project:
src
hbm.xml
cfg.xml
hibDomain(hibernate package)
rppctest.client (GWT package)
rppctest.server (GWT package)
I am using MySQL on Windows 7.
Here are the error messages & my code.
errors
94 [btpool0-2] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA
126 [btpool0-2] INFO org.hibernate.cfg.Environment - hibernate.properties not found
173 [btpool0-2] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
282 [btpool0-2] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
751 [btpool0-2] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
751 [btpool0-2] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
3657 [btpool0-2] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : user.hbm.xml
4018 [btpool0-2] INFO org.hibernate.cfg.HbmBinder - Mapping class: com.hib.User -> users
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
Starting Jetty on port 8888
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String rpctest.client.RpctestService.addUser(java.lang.String,java.lang.String) throws java.lang.IllegalArgumentException' threw an unexpected exception: java.lang.ExceptionInInitializerError
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:385)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:588)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: java.lang.ExceptionInInitializerError
at hibDomain.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at hibDomain.HibernateUtil.<clinit>(HibernateUtil.java:7)
at rpctest.server.RpctestServiceImpl.addUser(RpctestServiceImpl.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
... 22 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:602)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1621)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1589)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1568)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1542)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
at hibDomain.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 29 more
Caused by: org.hibernate.MappingException: class com.hib.User not found while looking for property: firstName
at org.hibernate.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:97)
at org.hibernate.mapping.SimpleValue.setTypeUsingReflection(SimpleValue.java:302)
at org.hibernate.cfg.HbmBinder.createProperty(HbmBinder.java:2193)
at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2170)
at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2060)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:381)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:295)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:166)
at org.hibernate.cfg.Configuration.add(Configuration.java:702)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:537)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:599)
... 36 more
Caused by: java.lang.ClassNotFoundException: com.hib.User
at java.lang.ClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:352)
at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:123)
at org.hibernate.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:93)
... 46 more
[ERROR] 500 - POST /rpctest/testService (127.0.0.1) 57 bytes
Request headers
Accept: */*
X-GWT-Permutation: HostedMode
X-GWT-Module-Base: http://127.0.0.1:8888/rpctest/
Content-Type: text/x-gwt-rpc; charset=utf-8
Referer: http://127.0.0.1:8888/Rpctest.html?gwt.codesvr=127.0.0.1:9997
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Host: 127.0.0.1:8888
Content-Length: 168
Connection: Keep-Alive
Cache-Control: no-cache
Response headers
Content-Type: text/plain
entry point class
package rpctest.client;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
final Label label1 = new Label("First Name");
final Label label2 = new Label("Last Name");
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync calNumbers = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
addpanel1.add(label1);
addpanel1.add(firstName);
addpanel2.add(label2);
addpanel2.add(lastName);
mainpanel.add(addpanel1);
mainpanel.add(addpanel2);
mainpanel.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
String name1 = firstName.getValue();
String name2 = lastName.getValue();
calNumbers.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
Window.alert("User is ->"+result);
}
});}
});
// We can add style names to widgets
//sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
/*RootPanel.get("nameFieldContainer").add(nameField);
*
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);*/
RootPanel.get().add(mainpanel);
}
}
interfaces
package rpctest.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("testService")
public interface RpctestService extends RemoteService {
String addUser(String firstName,String lastName) throws IllegalArgumentException;
}
package rpctest.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface RpctestServiceAsync {
void addUser(String firstName, String lastName,
AsyncCallback<String> callback);
}
Implementation
package rpctest.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import hibDomain.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import hibDomain.User;
import hibDomain.Task;
import rpctest.client.RpctestService;
public class RpctestServiceImpl extends RemoteServiceServlet implements RpctestService {
public String addUser(String name1, String name2)
throws IllegalArgumentException {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
User user = new User();
user.setFirstName(name1);
user.setLastName(name2);
session.save(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
return name1;
}
}
Hibernate files
package hibDomain;
public class User {
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
mapping file
<?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="com.hib.User" table="users" >
<id name="id" type="int" column="id" >
<generator class="native"/>
</id>
<property name="firstName">
<column name="first_name" />
</property>
<property name="lastName">
<column name="last_name"/>
</property>
</class>
</hibernate-mapping>
cfg file
<?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://localhost/userdata</property>
<property name="connection.username">root</property>
<property name="connection.password"></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 files -->
<mapping resource="user.hbm.xml"/>
<mapping resource="task.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Util
package hibDomain;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Your hibernate class file (User) is in "hibDomain" package. where as the mapping you are making is for "com.hib.User". change this to hibDomain.User and it might work.
So I have setup a MySQL database with table with one record. My Solution is made up of three projects (1 domain model library, test library and my Web project). In my MVC project I have implemented NHibernate with all necessary Dll's, and
In Web project root:
nhibernate-configuration.xsd
nhibernate-mapping.xsd
nhibernate.config and
<classname>.hbm.xml file - with the class it is mapping
In my Global.asax.cs file I have my event handlers to bind the current session:
public class MvcApplication : System.Web.HttpApplication
{
public MvcApplication()
{
BeginRequest += (MvcApplication_BeginRequest);
EndRequest += (MvcApplication_EndRequest);
}
void MvcApplication_BeginRequest(object sender, EventArgs e)
{
CurrentSessionContext.Bind(BootStrapper.SessionFactory.OpenSession());
}
void MvcApplication_EndRequest(object sender, EventArgs e)
{
CurrentSessionContext.Unbind(BootStrapper.SessionFactory).Dispose();
}
Then I have my BootStrapper class which returns the current session:
public static readonly ISessionFactory SessionFactory = CreateSessionFactory();
private static ISessionFactory CreateSessionFactory()
{
var cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nhibernate.config"));
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName);
return cfg.BuildSessionFactory();
}
public static ISession GetSession()
{
return SessionFactory.GetCurrentSession();
}
My Controller is being handed an object by my Ninject IoC
ProductController.cs
public class ProductsController : Controller
{
private readonly IProductsRepository productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
NinjectControllerFactory.cs
public class NinjectControllerFactory : DefaultControllerFactory
{
//Supplies Object instances
private IKernel kernel = new StandardKernel(new DaisyblossomsServices());
//MVC calls this to get the controller for each requests
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
return (Controller)kernel.Get(controllerType);
}
}
Which you will sell calls my services class DaisyblossomsServices:
public class DaisyblossomsServices : NinjectModule
{
public override void Load()
{
Bind<IProductsRepository>().To<ProductsRepository>();
}
}
Where you can see IProductsRepository is bound to my ProductsRepository class:
public class ProductsRepository : IProductsRepository
{
public IQueryable Products
{
get { var session = BootStrapper.GetSession();
return session.CreateCriteria(typeof(Product)).List<Product>().AsQueryable();
}
}
}
And my ProductsController is handed an IProductsRepository object
public interface IProductsRepository
{
IQueryable Products { get; }
}
As additional information My Product.hbm.xml file which maps my Product.cs class
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Daisyblossoms.Domain"
namespace="Daisyblossoms">
<class name="Product"
table="product">
<id name="ProductID">
<generator class="assigned" />
</id>
<property name="Name" column="Name" />
<property name="Price" column="Price" />
</class>
</hibernate-mapping>
And my nhibernate.config:
<?xml version="1.0"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="Daisyblossoms.Domain">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="generate_statistics">true</property>
<property name="current_session_context_class">web</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
<mapping assembly="Daisyblossoms.WebUI"/>
</session-factory>
</hibernate-configuration>
And my connectionsStrings part of Web.config:
<connectionStrings>
<add name="daisyblossoms" connectionString="Server=localhost;Port=3306;Database=dbName;Uid=user;Pwd=somePSWD;pooling=false;"
providerName="MySql.Data.MySqlClient"/>
Any thoughts what might be my issue?
Verify that hibernate.cfg.xml has output set to "Update if newer" and that your *.hbm.xml files are marked as Embedded Resources. Those are the two most common mistakes. It also sounds like you're trying to get a lot of moving parts working at the same time. You might want to simplify things to just get a console app to connect to MySQL using NHibernate. Something like this:
internal class Program {
private static void Main() {
var cfg = new Configuration();
cfg.Configure(); // Uses hibernate.cfg.xml by default.
// cfg.Configure("nhibernate.config"); // Or use this overload if you prefer your own name.
var sessionFactory = cfg.BuildSessionFactory();
using(var session = sessionFactory.OpenSession())
using(var tx = session.BeginTransaction()) {
var query = session.CreateCriteria<Product>().List();
query.ForEach(x => Console.WriteLine(x.Name));
tx.Commit();
}
Console.WriteLine("Press <ENTER> to exit...");
Console.ReadLine();
}
}
This would allow you to verify that your mappings and configuration files are correct without worrying about MVC, Ninject, etc. at the same time.