初学 struts2 + spring3 + hibernate4 很是头疼,网上找了很多代码都不能直用,于是花了好久总算研究出个结果.
希望通过这篇文章给自己加深印象并且让像我一样的新手少绕点弯.
------------------------------------------------我是分割线-----------------------------------------------------------------
首先是pojo类
@Entity
@Table(name="user")
@Embeddable
public class users {
@Id
@Column(name = "Id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int id;
@Column(name = "firstname" ,
unique = true ,
nullable = false ,
length = 30
)
public String firstname;
@Column(name = "lastname" ,
unique = true ,
nullable = false ,
length = 30
)
public String lastname;
@Column(name = "age" ,
nullable = false ,
length = 2
)
public int age;
//省略getter和setter方法
然后是applicationContext.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" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hiernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.bean.users</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 下面的dao/services类注入配置不写额, 自己找书, 都一样的-->
<!-- 配置 spring 用于连接数据库的Bean设置及与hibnate启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置 struts 主要用于struts标签 启用及相关方面 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
依赖包
推荐一个csdn会员的分享, 里面的包很全, 虽然我没有用他的
http://download.csdn.net/detail/u010653050/5356421
非常感谢这位哥
----------------------------------------------------------我是分割线----------------------------------------------------------------
上述配置代码由hibernate4的annotation直接驱动数据库对象
就是说我们不需要对数据表做hibernate映射了,annotaton已经帮我们省略了这个部分