one-to-many relationship with table having composite key - hibernate-mapping

This is the full code for mapping of the tables I am doing. But dont know why I am getting
java heap space error. I am using Jboss server and the exact error message is java.lang.OutOfMemoryError: Java heap space.
package com.mercer.chat.app.dataobject;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MHRContChatSessionDO {
private Long id;
private String chatBucketHeadline;
private String preChatLongHeadline;
private String postChatLongHeadline;
private String preChatSummary;
private String postChatSummary;
private String chatBucketImage;
private String chatLogPath;
private Integer roomId;
private List<MHRContChatAlertsDO> chatAlerts;
public MHRContChatSessionDO() {
super();
}
public MHRContChatSessionDO(Long id, String chatBucketHeadline, String preChatLongHeadline,
String postChatLongHeadline, String preChatSummary, String postChatSummary, String chatBucketImage,
String chatLogPath,Integer roomId, List<MHRContChatAlertsDO> chatAlerts) {
super();
this.id = id;
this.chatBucketHeadline = chatBucketHeadline;
this.preChatLongHeadline = preChatLongHeadline;
this.postChatLongHeadline = postChatLongHeadline;
this.preChatSummary = preChatSummary;
this.postChatSummary = postChatSummary;
this.chatBucketImage = chatBucketImage;
this.chatLogPath = chatLogPath;
this.roomId = roomId;
this.chatAlerts = chatAlerts;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChatBucketHeadline() {
return chatBucketHeadline;
}
public void setChatBucketHeadline(String chatBucketHeadline) {
this.chatBucketHeadline = chatBucketHeadline;
}
public String getPreChatLongHeadline() {
return preChatLongHeadline;
}
public void setPreChatLongHeadline(String preChatLongHeadline) {
this.preChatLongHeadline = preChatLongHeadline;
}
public String getPostChatLongHeadline() {
return postChatLongHeadline;
}
public void setPostChatLongHeadline(String postChatLongHeadline) {
this.postChatLongHeadline = postChatLongHeadline;
}
public String getPreChatSummary() {
return preChatSummary;
}
public void setPreChatSummary(String preChatSummary) {
this.preChatSummary = preChatSummary;
}
public String getPostChatSummary() {
return postChatSummary;
}
public void setPostChatSummary(String postChatSummary) {
this.postChatSummary = postChatSummary;
}
public String getChatBucketImage() {
return chatBucketImage;
}
public void setChatBucketImage(String chatBucketImage) {
this.chatBucketImage = chatBucketImage;
}
public String getChatLogPath() {
return chatLogPath;
}
public void setChatLogPath(String chatLogPath) {
this.chatLogPath = chatLogPath;
}
public Integer getRoomId() {
return roomId;
}
public void setRoomId(Integer roomId) {
this.roomId = roomId;
}
public List<MHRContChatAlertsDO> getChatAlerts() {
return chatAlerts;
}
public void setChatAlerts(List<MHRContChatAlertsDO> chatAlerts) {
this.chatAlerts = chatAlerts;
}
}
public class MHRContChatAlertsDO implements Serializable {
private Long id;
private String userId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public MHRContChatAlertsDO() {
}
public MHRContChatAlertsDO(Long id,String userId) {
this.id=id;
this.userId=userId;
}
#Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof MHRContChatAlertsDO)) return false;
MHRContChatAlertsDO arg1 = (MHRContChatAlertsDO) arg0;
return (this.id.longValue() == arg1.getId().longValue()) && (this.userId.equals(arg1.getUserId()) );
}
#Override
public int hashCode() {
int hsCode;
hsCode = id.hashCode();
hsCode = 19 * hsCode+ userId.hashCode();
return hsCode;
}
}
<?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 default-lazy="true">
<class name="com.mercer.chat.app.dataobject.MHRContChatSessionDO"
table="QA_TEST2">
<cache usage="read-only" include="all"/>
<id name="id" type="java.lang.Long">
<column name="ID_CHAT_SESSION" precision="22" scale="0" />
<generator class="assigned" />
</id>
<property name="chatBucketHeadline" type="string">
<column name="CHAT_BUCKET_HEADLINE" />
</property>
<property name="preChatLongHeadline" type="string">
<column name="PRE_CHAT_LONGHEADLINE" scale="0" />
</property>
<property name="postChatLongHeadline" type="string">
<column name="POST_CHAT_LONGHEADLINE" />
</property>
<property name="preChatSummary" type="string">
<column name="PRE_CHAT_SUMMARY" />
</property>
<property name="postChatSummary" type="string">
<column name="POST_CHAT_SUMMARY" not-null="true" />
</property>
<property name="chatBucketImage" type="string">
<column name="CHAT_BUCKET_IMAGE_PATH" />
</property>
<property name="chatLogPath" type="string">
<column name="CHAT_LOG_PATH" />
</property>
<property name="roomId" type="java.lang.Integer">
<column name="ROOM_ID" scale="0" />
</property>
<list name="chatAlerts" batch-size="5" cascade="all" lazy="false">
<cache usage="read-only" include="all" />
<key column="ID_CHAT_SESSION" />
<list-index column="ID_USER" />
<one-to-many
class="com.mercer.chat.app.dataobject.MHRContChatAlertsDO" />
</list>
</class>
</hibernate-mapping>
<hibernate-mapping default-lazy="true">
<class name="com.mercer.chat.app.dataobject.MHRContChatAlertsDO" table="QA_TEST3">
<cache usage="read-only" include="all" />
<composite-id >
<key-property name="id" type="java.lang.Long">
<column name="ID_CHAT_SESSION" precision="22" scale="0" />
</key-property>
<key-property name="userId" type="string">
<column name="ID_USER" />
</key-property>
</composite-id>
</class>
</hibernate-mapping>

Related

Spring mvc MappingSqlQuery Property 'sql' is required

I work with Netbeans, Spring MVC and Oracle.
I want to use MappingSqlQuery to execute oracle sql. This is the java class which implements MappingSqlQuery
public class SelectAllDepartamentos extends MappingSqlQuery<Departamento> {
private static final String SQL_SELECT_DEPT =
"SELECT DEPT_NO, DNOMBRE, LOC FROM DEPT";
public SelectAllDepartamentos() {
}
public SelectAllDepartamentos(DataSource dataSource) {
super(dataSource,SQL_SELECT_DEPT);
}
#Override
protected Departamento mapRow(ResultSet rs, int i) throws SQLException {
Departamento dept = new Departamento();
dept.setNumero(rs.getInt("DEPT_NO"));
dept.setNombre(rs.getString("DNOMBRE"));
dept.setLocalidad(rs.getString("LOC"));
return dept;
}
}
The class which use SelectAllDepartamentos is . The method that I use is findAll
public class JdbcDepartamentoDao1 implements InitializingBean,DepartamentoDao{
private javax.sql.DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private SelectAllDepartamentos selectdepartamentos;
public JdbcDepartamentoDao1() {
}
public JdbcDepartamentoDao1(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
}
public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}
#Override
public List<Departamento> findAll() {
return this.selectdepartamentos.execute();
}
#Override
public List<Departamento> findByLocalidad(String localidad) {
return null;
}
#Override
public String findById(int iddepartamento) {
String nombre = jdbcTemplate.queryForObject("SELECT DNOMBRE from DEPT WHERE DEPT_NO = ?",
new Object[]{iddepartamento},String.class);
return nombre;
}
#Override
public void insertarDepartamento(Departamento departamento) {
}
#Override
public void modificarDepartamento(Departamento departamento) {
}
#Override
public void eliminarDepartamento(Departamento departamento) {
}
#Override
public void afterPropertiesSet() throws Exception {
if (dataSource == null){
throw new BeanCreationException("Debe establece el dataSource ContactDao");
}
}
}
My application-context.xml is
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="departamentoDao" class="dao.JdbcDepartamentoDao1">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
<bean id="selectAllDepartamentos" class="modelos.SelectAllDepartamentos">
<property name="dataSource" ref="dataSource"></property>
<constructor-arg type="DataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
When I executed the method findAll
#Override
public List<Departamento> findAll() {
return this.selectdepartamentos.execute();
}
I get the error
Remove
/*public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}*/
Change to arg
<bean id="departamentoDao" class="dao.JdbcDepartamentoDao1">
<constructor-arg ref="dataSource" />
</bean>
Update constructor
public JdbcDepartamentoDao1(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}

Exception: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource

I created a spring project (Spring 4.0.2). I present the required files:
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeDAO" class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="employeeDAOJDBCTemplate" class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;database=springdb"/>
<property name="username" value="lm" />
<property name="password" value="pp" />
</bean>
</beans>
Employee.java
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
// with getters, setters, default constructor, constructor using fields
}
EmployeeDAO.java
public interface EmployeeDAO
{
public List<Employee> getAll();
}
EmployeeDAOImpl.java
public class EmployeeDAOImpl implements EmployeeDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
List<Employee> empList = new ArrayList<Employee>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()){
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
empList.add(emp);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return empList;
}
}
EmployeeDAOJDBCTemplateImpl.java
public class EmployeeDAOJDBCTemplateImpl implements EmployeeDAO,Serializable {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Employee> empList = new ArrayList<Employee>();
List<Map<String,Object>> empRows = jdbcTemplate.queryForList(query);
for(Map<String,Object> empRow : empRows){
Employee emp = new Employee();
emp.setId(Integer.parseInt(String.valueOf(empRow.get("id"))));
emp.setName(String.valueOf(empRow.get("name")));
emp.setRole(String.valueOf(empRow.get("role")));
empList.add(emp);
}
return empList;
}
}
The bean to call in order to extract the list of employees DataModelD.java :
#ManagedBean
#ViewScoped
public class DataModelD implements Serializable
{
private List<Employee> list;
private Employee employee;
private EmployeeDAO eDao;
#PostConstruct
public void init()
{
System.out.println("-----------------------------BEGIN List");
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
eDao = ctx.getBean("employeeDAOJDBCTemplate", EmployeeDAO.class);
employee = new Employee();
list = eDao.getAll();
System.out.println("---------------------------------------List size= " + list.size());
}
}
After running it(to display the list of employees), the following exception is displayed:
08:14:46,222 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HiSpring.war"
08:15:29,271 INFO [stdout] (http-localhost-127.0.0.1-8080-1) -----------------------------BEGIN List
08:15:29,529 INFO [org.springframework.context.support.ClassPathXmlApplicationContext] (http-localhost-127.0.0.1-8080-1) Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#ca34ed: startup date [Wed Aug 17 08:15:29 GMT-08:00 2016]; root of context hierarchy
08:15:29,591 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] (http-localhost-127.0.0.1-8080-1) Loading XML bean definitions from class path resource [spring.xml]
08:15:29,718 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource] (http-localhost-127.0.0.1-8080-1) Loaded JDBC driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
08:15:30,736 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ---------------------------------------List size= 5
08:15:30,832 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8080-1) Error Rendering View[/sarsoura/list.xhtml]: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource
at java.io.ObjectOutputStream.writeObject0(Unknown Source) [rt.jar:1.7.0_55]
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) [rt.jar:1.7.0_55]
Have you please any idea about this issue?.Any reply will be appreciated.

sql datasource in blueprint.xml in servicemix

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433/orderdb"/>
<property name="username" value="abc"/>
<property name="password" value="pqr"/>
</bean>
When i try to make connection using dataSource.getConnection()
Not allowing please help
*****Connection Code **********
public class DatabaseBeanH2 {
private DataSource dataSource;
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseBeanH2.class);
public DatabaseBeanH2(){}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void create() throws SQLException{
Statement sta = dataSource.getConnection().createStatement();
try {
sta.executeUpdate("CREATE TABLE orders ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, item VARCHAR(50), amount INT, description VARCHAR(300), processed BOOLEAN, consumed BOOLEAN);");
} catch (SQLException e) {
LOGGER.info("Table orders already exists");
}
}
public void destroy() throws SQLException {
dataSource.getConnection().close();
}
}
You have to inject the dataSource bean in your DatabaseBeanH2 in the camel/spring context, something like this:
<bean id="databaseBean" class="my.package.DatabaseBeanH2">
<property name="dataSource" ref="dataSource" />
</bean>

nhibernate, could not resolve property QueryOver only one table

I have found a dozen of question similar to mine but none of them offered a solution to my problem.
Thank you in advance
Ok,
I have this class
public class User : IEntity
{
private int id;
public virtual int Id { get { return id; } }
private string email;
public virtual string Email
{
get { return email; }
//private set { email = value; }
}
private string password;
public virtual string Password
{
get { return password; }
//private set { password = value; }
}
private bool isActive;
public virtual bool IsActive
{
get { return isActive; }
//private set { isActive = value; }
}
private bool isRegistered;
public virtual bool IsRegistered
{
get { return isRegistered; }
//private set { isRegistered = value; }
}
private bool hasRequestedApplication;
public virtual bool HasRequestedApplication
{
get { return hasRequestedApplication; }
//private set { hasRequestedApplication = value; }
}
private ContactInfo contactInformation;
public virtual ContactInfo ContactInformation
{
get { return contactInformation; }
//private set { contactInformation = value; }
}
public User(string email)
{
this.email = email;
}
public User(string email, string password):this(email)
{
this.password = password;
}
public User()
{ }
}
this is the mapping....
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain"
namespace="Domain.User" default-access="field">
<class name="User" table="[User]">
<id name="id" column="UserID">
<generator class="identity" />
</id>
<property name="email" column="Email" not-null="true"></property>
<property name="password" column="HashedPassword" not-null="false"></property>
<property name="isRegistered" column="IsRegistered" not-null="true"></property>
<property name="isActive" column="IsActive" not-null="true"></property>
<property name="hasRequestedApplication" column="HasRequestedApplication" not-null="true"></property>
<one-to-one name="contactInformation" class="Domain.User.ContactInfo"/>
</class>
</hibernate-mapping>
and this is how i am calling it
public class UserRepository: IUserRepository
{
Func<ISession> session;
public UserRepository(Func<ISession> _session)
{
session = _session;
}
[Transaction]
public User FindByEmail(string emailAddress)
{
using (var tx = session())
{
return tx.QueryOver<User>().Where(u => u.Email == emailAddress).SingleOrDefault();
}
}
}
Error...
{"could not resolve property: Email of: Domain.User.User"}
StackTrace...
at NHibernate.Persister.Entity.AbstractPropertyMapping.ToType(String propertyName)
at NHibernate.Persister.Entity.AbstractEntityPersister.GetSubclassPropertyTableNumber(String propertyPath)
at NHibernate.Persister.Entity.BasicEntityPropertyMapping.ToColumns(String alias, String propertyName)
at NHibernate.Persister.Entity.AbstractEntityPersister.ToColumns(String alias, String propertyName)
at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumns(ICriteria subcriteria, String propertyName)
at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumnsUsingProjection(ICriteria subcriteria, String propertyName)
at NHibernate.Criterion.CriterionUtil.GetColumnNamesUsingPropertyName(ICriteriaQuery criteriaQuery, ICriteria criteria, String propertyName, Object value, ICriterion critertion)
at NHibernate.Criterion.SimpleExpression.ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary2 enabledFilters)
at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetWhereCondition(IDictionary2 enabledFilters)
at NHibernate.Loader.Criteria.CriteriaJoinWalker..ctor(IOuterJoinLoadable persister, CriteriaQueryTranslator translator, ISessionFactoryImplementor factory, ICriteria criteria, String rootEntityName, IDictionary2 enabledFilters)
at NHibernate.Loader.Criteria.CriteriaLoader..ctor(IOuterJoinLoadable persister, ISessionFactoryImplementor factory, CriteriaImpl rootCriteria, String rootEntityName, IDictionary2 enabledFilters)
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
at NHibernate.Impl.CriteriaImpl.List(IList results)
at NHibernate.Impl.CriteriaImpl.UniqueResultT
at NHibernate.Criterion.QueryOver1.SingleOrDefault()
at NHibernate.Criterion.QueryOver1.NHibernate.IQueryOver.SingleOrDefault()
at DataObjects.NHibernate.UserRepository.FindByEmail(String emailAddress) in E:\Projects\DataObjects.NHibernate\UserRepository.cs:line 26
at Castle.Proxies.Invocations.IUserRepository_FindByEmail.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Facilities.AutoTx.TransactionInterceptor.SynchronizedCase(IInvocation invocation, ITransaction transaction) in d:\BuildAgent-03\work\9844bdf039249947\src\Castle.Facilities.AutoTx\TransactionInterceptor.cs:line 137
EDIT:
OK. Solved to some extent. I changed all my properties and components name to capital in my mapping.
Instead of...
<property name="email" column="emailaddress" />
set it to...
<property name="Email" column="emailaddress" />
and it works. Now, is that a guarantee that NHibernate is populating/reading my properties via the fields? I hope so.
This should help: Change the settings to be different for get and set
<hibernate-mapping ... default-access="field.camelcase">
and map the properties:
<property name="Email" column="emailaddress" />
NHibernate will use field for set and the Property for get. This QueryOver:
return tx.QueryOver<User>()
.Where(u => u.Email == emailAddress)
.SingleOrDefault();
...will work now
I believe the "name" of the properties in your mapping should match the case of the public virtual properties in your class. Try changing <property name="email"... to <property name="Email"... and so on.

NHibernate Does Not Popluate DB Record

I am new to NHibernate and have been working with some tutorials. I created an object (Project) and passed it to the Session.Save(obj) method. To test, I had default values in each DB field and the method returned the primary key but the fields were blank. I removed the default values from the DB and I get a SQL error "cannot insert NULL into the first field".
Here is the Project class:
public class Project
{
private int _projectId;
public virtual int ProjectId
{
get { return _projectId; }
set { _projectId = value; }
}
private string _projectCode;
public virtual string ProjectCode
{
get { return _projectCode; }
set { _projectCode = value; }
}
private int _customerKey;
public virtual int CustomerKey
{
get { return _customerKey; }
set { _customerKey = value; }
}
private DateTime _insertDate;
public virtual DateTime InsertDate
{
get { return _insertDate; }
set { _insertDate = value; }
}
}
Here is the mapping file:Project.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.2"
assembly="MosaicCrm.Core"
namespace="MosaicCrm.Core">
<class name="Project" >
<id name="ProjectId">
<generator class="native"></generator>
</id>
<properties name="ProjectCode" ></properties>
<properties name="CustomerKey"></properties>
<properties name="InsertDate"></properties>
</class>
</hibernate-mapping>
Here is the config file.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2005Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=localhost;Initial Catalog=MosaicCrm;Integrated Security=SSPI;
</property>
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
</session-factory>
</hibernate-configuration>
Here is a snippet of the console app
var config = new Configuration();
config.Configure();
//config.AddAssembly(typeof(Project).Assembly);
config.AddAssembly("MosaicCrm.Core");
var factory = config.BuildSessionFactory();
//TODO: NHibernate access code here
ISession session = null;
ITransaction trans = null;
try
{
session = factory.OpenSession();
trans = session.BeginTransaction();
var project = new Project();
project.CustomerKey = 12;
project.ProjectCode = "ProjectCode";
project.InsertDate = DateTime.Now;
session.Save(project);
trans.Commit();
int i = project.ProjectId;
}
catch (Exception ex)
{
trans.Rollback();
}
finally
{
session.Close();
}
What am I doing missing?
Your mapping is wrong. The element used to map a property is property, not properties.