day01--项目框架搭建
1.数据库测试表
CREATE TABLE Elec_Text(
textID varchar(50) not null primary key,
textName varchar(50),
textDate datetime,
textRemark varchar(500)
)
2.持久层
package cn.itcast.elec.domain;
import java.util.Date;
@SuppressWarnings("serial")
public class ElecText implements java.io.Serializable {
private String textID; //测试ID
private String textName; //测试名称
private Date textDate; //测试日期
private String textRemark; //测试备注
public String getTextID() {
return textID;
}
public void setTextID(String textID) {
this.textID = textID;
}
public String getTextName() {
return textName;
}
public void setTextName(String textName) {
this.textName = textName;
}
public Date getTextDate() {
return textDate;
}
public void setTextDate(Date textDate) {
this.textDate = textDate;
}
public String getTextRemark() {
return textRemark;
}
public void setTextRemark(String textRemark) {
this.textRemark = textRemark;
}
}
<?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="cn.itcast.elec.domain.ElecText" table="Elec_Text">
<id name="textID" type="string" column="textID">
<generator class="uuid"></generator>
</id>
<property name="textName" type="string" column="textName"></property>
<property name="textDate" type="date" column="textDate"></property>
<property name="textRemark" type="string" column="textRemark"></property>
</class>
</hibernate-mapping>
3.全局配置文件
hibernate.cfg.xml
<?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>
<!-- 连接数据库的信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/elecproject?useUnicode=true&characterEncoding=utf8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">111</property>
<!-- hibernate自动提交事务
<property name="hibernate.connection.autocommit">true</property>-->
<!-- 其它配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<!-- 加载映射文件 -->
<mapping resource="cn/itcast/elec/domain/ElecText.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.junit测试
TestHibernate.java
package junit;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import cn.itcast.elec.domain.ElecText;
public class TestHibernate {
/**保存*/
@Test
public void save(){
Configuration configuration = new Configuration();
//默认加载类路径下的hibernate.cfg.xml,同时加载映射文件
configuration.configure();
SessionFactory sf = configuration.buildSessionFactory();
Session s = sf.openSession();
Transaction tr = s.beginTransaction();
ElecText elecText = new ElecText();
elecText.setTextName("测试Hibernate名称");
elecText.setTextDate(new Date());
elecText.setTextRemark("测试Hibernate备注");
s.save(elecText);
tr.commit();
s.close();
}
}
5.log4j日志
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=error, stdout
#log4j.logger.org.hibernate=info
### log just the SQL
#log4j.logger.net.sf.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log cache activity ###
#log4j.logger.net.sf.hibernate.cache=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trace
6.beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 1:注解的方式,引入组件的自动扫描,在类和方法上可以添加对注解的支持 -->
<context:component-scan base-package="cn.itcast.elec"/>
<!-- 2:? -->
<!-- 3:创建sessionFactory对象,这是spring整合hibernate的核心 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- 4:创建事务管理器 -->
<bean id="trManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 5:注解:切面:用业务层管理事务,在业务层的代码中@Transcational -->
<tx:annotation-driven transaction-manager="trManager"/>
<!-- 5:XML,配置文件的写法,管理事务
<tx:advice id="aa" transaction-manager="trManager">
<tx:attributes>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="bb" expression="execution(* cn.itcast.elec.service..*.*(..))" />
<aop:advisor advice-ref="aa" pointcut-ref="bb"/>
</aop:config>
-->
</beans>
7.DAO+IMPL
ICommonDao.java
package cn.itcast.elec.dao;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface ICommonDao<T> {
void save(T entity);
void update(T entity);
T findObjectByID(Serializable id);
void deleteBojectByIDs(Serializable... ids);
void deleteObjectByCollection(List<T> list);
List<T> findCollectionByConditionNoPage(String condition,
Object[] params, Map<String, String> orderby);
}
IElecTextDao.java
package cn.itcast.elec.dao;
import cn.itcast.elec.domain.ElecText;
public interface IElecTextDao extends ICommonDao<ElecText> {
public static final String SERVICE_NAME = "cn.itcast.elec.dao.impl.ElecTextDaoImpl";
}
CommonDaoImpl.java
package cn.itcast.elec.dao.impl;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.itcast.elec.dao.ICommonDao;
import cn.itcast.elec.util.GenericTypeUtils;
public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> {
Class entityClass = GenericTypeUtils.getGenericSuperClass(this.getClass());
/**
* spring容器中定义
* <bean id="commonDao" class="cn.itcast.elec.dao.impl.CommonDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
*/
@Resource(name="sessionFactory")
public final void setSessionFactoryDi(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
/**保存*/
public void save(T entity) {
this.getHibernateTemplate().save(entity);
}
/**更新*/
public void update(T entity) {
this.getHibernateTemplate().update(entity);
}
/**使用主键ID查询对象*/
public T findObjectByID(Serializable id) {
return (T) this.getHibernateTemplate().get(entityClass, id);
}
/**删除(使用1个主键ID和多个主键ID的数组)*/
public void deleteBojectByIDs(Serializable... ids) {
if(ids!=null && ids.length>0){
for(Serializable id:ids){
Object entity = this.findObjectByID(id);
this.getHibernateTemplate().delete(entity);
}
}
}
/**删除(将对象封装成集合,使用集合删除集合中存放的所有对象)*/
/**用法:将数据查询获取封装到List中,删除全部的list,先查询再删除*/
public void deleteObjectByCollection(List<T> list) {
this.getHibernateTemplate().deleteAll(list);
}
/**指定页面传递的查询条件,查询对应的结果集信息,返回List<ElecText>,不分页*/
/**
SELECT * FROM elec_text o WHERE 1=1 #Dao层
AND o.textName LIKE '%张%' #Service层
AND o.textRemark LIKE '%张%' #Service层
ORDER BY o.textDate ASC,o.textRemark DESC #Service层
*/
public List<T> findCollectionByConditionNoPage(String condition,
final Object[] params, Map<String, String> orderby) {
String hql = "select o from "+entityClass.getSimpleName()+" o where 1=1 ";
//解析map集合,获取排序的语句
String orderbyhql = this.orderby(orderby);
final String finalHql = hql + condition + orderbyhql;
//方式一
//List<T> list = this.getHibernateTemplate().find(finalHql, params);
//方式二,使用hibernate模板提供的回调函数,回调Session
List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(finalHql);
if(params!=null && params.length>0){
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
return query.list();
}
});
return list;
}
//解析map集合,获取排序的语句,ORDER BY o.textDate ASC,o.textRemark DESC
private String orderby(Map<String, String> orderby) {
StringBuffer buffer = new StringBuffer("");
if(orderby!=null && orderby.size()>0){
buffer.append(" order by ");
for(Map.Entry<String, String> map:orderby.entrySet()){
buffer.append(map.getKey()+" "+map.getValue()+",");
}
//删除最后一个逗号
buffer.deleteCharAt(buffer.length()-1);
}
return buffer.toString();
}
}
ElecTextDaoImpl.java
package cn.itcast.elec.dao.impl;
import org.springframework.stereotype.Repository;
import cn.itcast.elec.dao.IElecTextDao;
import cn.itcast.elec.domain.ElecText;
/**
* 相当于spring容器中定义:
* <bean id="cn.itcast.elec.dao.impl.ElecTextDaoImpl" class="cn.itcast.elec.dao.impl.ElecTextDaoImpl">
*
* </bean>
*
*/
@Repository(IElecTextDao.SERVICE_NAME)
public class ElecTextDaoImpl extends CommonDaoImpl<ElecText> implements IElecTextDao {
}
8.service
IElecTextService.java
package cn.itcast.elec.service;
import java.util.List;
import cn.itcast.elec.domain.ElecText;
public interface IElecTextService {
public static final String SERVICE_NAME = "cn.itcast.elec.service.impl.ElecTextServiceImpl";
public void save(ElecText elecText);
public List<ElecText> findCollectionByConditionNoPage(ElecText elecText);
}
ElecTextServiceImpl.java
package cn.itcast.elec.service.impl;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.elec.dao.IElecTextDao;
import cn.itcast.elec.domain.ElecText;
import cn.itcast.elec.service.IElecTextService;
@Service(IElecTextService.SERVICE_NAME)
@Transactional(readOnly=true)
public class ElecTextServiceImpl implements IElecTextService {
@Resource(name=IElecTextDao.SERVICE_NAME)
private IElecTextDao elecTextDao;
/**保存*/
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public void save(ElecText elecText) {
elecTextDao.save(elecText);
}
/**指定页面传递的查询条件,查询对应的结果集信息,返回List<ElecText>*/
/**
SELECT * FROM elec_text o WHERE 1=1 #Dao层
AND o.textName LIKE '%张%' #Service层
AND o.textRemark LIKE '%张%' #Service层
ORDER BY o.textDate ASC,o.textRemark DESC #Service层
*/
public List<ElecText> findCollectionByConditionNoPage(ElecText elecText) {
//组织查询条件
String condition = "";
//存放可变参数?
List<Object> paramsList = new ArrayList<Object>();
if(StringUtils.isNotBlank(elecText.getTextName())){
condition += " and o.textName like ?";
paramsList.add("%"+elecText.getTextName()+"%");
}
if(StringUtils.isNotBlank(elecText.getTextRemark())){
condition += " and o.textRemark like ?";
paramsList.add("%"+elecText.getTextRemark()+"%");
}
//将集合中存放的可变参数转换成数组
Object [] params = paramsList.toArray();
//使用集合存放排序的条件(有序排列)
Map<String, String> orderby = new LinkedHashMap<String, String>();
orderby.put("o.textDate", "asc");
orderby.put("o.textRemark", "desc");
List<ElecText> list = elecTextDao.findCollectionByConditionNoPage(condition,params,orderby);
return list;
}
}
测试dao与service
TestDao.java
package junit;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.elec.dao.IElecTextDao;
import cn.itcast.elec.domain.ElecText;
public class TestDao {
/**保存*/
@Test
public void save(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);
ElecText elecText = new ElecText();
elecText.setTextName("测试Dao名称");
elecText.setTextDate(new Date());
elecText.setTextRemark("测试Dao备注");
elecTextDao.save(elecText);
}
/**更新*/
@Test
public void update(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);
ElecText elecText = new ElecText();
elecText.setTextID("402881e442599916014259991c450001");
elecText.setTextName("更新名称");
elecText.setTextDate(new Date());
elecText.setTextRemark("更新备注");
elecTextDao.update(elecText);
}
/**使用主键ID查询对象*/
@Test
public void findObjectById(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);
Serializable id = "402881e4425a729301425a734c2a0001";
ElecText elecText = elecTextDao.findObjectByID(id);
System.out.println(elecText.getTextName()+" "+elecText.getTextDate()+" "+elecText.getTextRemark());
}
/**删除(使用1个主键ID和多个主键ID的数组)*/
@Test
public void deleteObjectByIDs(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);
//Serializable [] ids = {"402881e442599916014259991c450001","402881e44259d1c0014259d1c48b0001"};
Serializable ids = "402881e44259de3a014259de40e40001";
elecTextDao.deleteBojectByIDs(ids);
}
/**删除(将对象封装成集合,使用集合删除集合中存放的所有对象)*/
@Test
public void deleteObjectByCollection(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);
List<ElecText> list = new ArrayList<ElecText>();
ElecText elecText1 = new ElecText();
elecText1.setTextID("402881e44259dfc5014259dfcaa10001");
ElecText elecText2 = new ElecText();
elecText2.setTextID("402881e44259e338014259e36de70001");
list.add(elecText1);
list.add(elecText2);
elecTextDao.deleteObjectByCollection(list);
}
}
TestService.java
package junit;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.elec.domain.ElecText;
import cn.itcast.elec.service.IElecTextService;
public class TestService {
/**保存*/
@Test
public void save(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextService elecTextService = (IElecTextService)ac.getBean(IElecTextService.SERVICE_NAME);
ElecText elecText = new ElecText();
elecText.setTextName("测试Service名称");
elecText.setTextDate(new Date());
elecText.setTextRemark("测试Service备注");
elecTextService.save(elecText);
}
/**模拟Action层,调用Service层*/
@Test
public void findCollectionByConditionNoPage(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
IElecTextService elecTextService = (IElecTextService)ac.getBean(IElecTextService.SERVICE_NAME);
ElecText elecText = new ElecText();
// elecText.setTextName("张");
// elecText.setTextRemark("张");
List<ElecText> list = elecTextService.findCollectionByConditionNoPage(elecText);
if(list!=null && list.size()>0){
for(ElecText text:list){
System.out.println(text.getTextName()+" "+text.getTextDate()+" "+text.getTextRemark());
}
}
}
}
控制层+封装ACTION
BaseAction.java
package cn.itcast.elec.web.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import cn.itcast.elec.util.GenericTypeUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>,ServletRequestAware,ServletResponseAware {
protected HttpServletRequest request;
protected HttpServletResponse response;
private T entity;
public BaseAction(){
//泛型转换
Class entityClass = GenericTypeUtils.getGenericSuperClass(this.getClass());
try {
entity = (T) entityClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public T getModel() {
return entity;
}
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
public void setServletResponse(HttpServletResponse res) {
this.response = res;
}
}
ElecTextAction.java
package cn.itcast.elec.web.action;
import javax.annotation.Resource;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import cn.itcast.elec.domain.ElecText;
import cn.itcast.elec.service.IElecTextService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
* 相当于spring容器中定义
* <bean id="elecTextAction" class="cn.itcast.elec.web.action.ElecTextAction">
*
*/
@SuppressWarnings("serial")
@Controller("elecTextAction")
@Scope(value="prototype")
public class ElecTextAction extends BaseAction<ElecText> {
private ElecText elecText = this.getModel();
@Resource(name=IElecTextService.SERVICE_NAME)
private IElecTextService elecTextService;
/**保存*/
public String save(){
elecTextService.save(elecText);
return "save";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<display-name></display-name>
<!-- 当web容器启动的时候,自动加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 添加struts2的过滤器,这是struts2执行的核心 -->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
http://download.youkuaiyun.com/detail/hoho_12/9761228