1. 程式人生 > >Maven 整合 SpringMvc Spring Hibernate +oracle

Maven 整合 SpringMvc Spring Hibernate +oracle

一、實習已經有大半年了 企業的專案都是搭建好的 自己也學習了去搭建一個 基於SSH的專案整合 其中查閱了很多資料 遇到一些問題也解決了。希望大家可以共同進步。

 感謝http://blog.csdn.net/js931178805/article/details/39642743這篇文章。

二、搭建maven專案 

(1)新建maven專案

 <1>我們選Maven Project



<2>選擇maven-archetype-webapp 


<3> 填寫專案資訊


<4> 補全目錄 右鍵--> bulid path 

 

專案基本結構


三、整合jetty  主要在pom 檔案 新增配置

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>sms</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sms Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
   	 <plugins>
  		 <plugin>  
			    <groupId>org.mortbay.jetty</groupId>  
			    <artifactId>maven-jetty-plugin</artifactId>  
			    <version>6.1.26</version>  
			    <configuration>               
			        <scanIntervalSeconds>3</scanIntervalSeconds>  
			        <connectors>  
			            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">  
			                <port>8090</port>  
			            </connector>  
			        </connectors>                     
			        <scanTargetPatterns>  
			            <scanTargetPattern>  
			                <directory>src/main/webapp/WEB-INF</directory>  
			                <excludes>  
			                    <exclude>**/*.jsp</exclude>  
			                </excludes>  
			                <includes>  
			                    <include>**/*.properties</include>  
			                    <include>**/*.xml</include>  
			                </includes>  
			            </scanTargetPattern>  
			        </scanTargetPatterns>  
			    </configuration>  
			</plugin>
		</plugins>
    <finalName>sms</finalName>
  </build>
</project>

jetty:run



開啟瀏覽器 訪問 http://localhost:8090/sms/index.jsp


四、利用maven來下載所有的jar 

pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>sms</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sms Maven Webapp</name>
  <url>http://maven.apache.org</url>
 
     <!-- 指定maven倉庫 -->  
    <repositories><!-- 發現依賴和擴充套件的遠端資源庫 -->  
        <!-- maven自己官方倉庫 -->  
        <repository>  
            <id>maven</id>  
            <name>Maven Repository Switchboard</name>  
            <layout>default</layout>  
            <url>http://repo1.maven.org/maven2</url>  
            <snapshots>  
                <enabled>false</enabled>  
            </snapshots>  
        </repository>  
        <!-- 阿里巴巴釋出版本倉庫 -->  
        <repository>  
            <id>alibaba-opensource</id>  
            <name>alibaba-opensource</name>  
            <url>http://code.alibabatech.com/mvn/releases/</url>  
            <layout>default</layout>  
        </repository>  
        <!-- 阿里巴巴快照版本倉庫 -->  
        <repository>  
            <id>alibaba-opensource-snapshot</id>  
            <name>alibaba-opensource-snapshot</name>  
            <url>http://code.alibabatech.com/mvn/snapshots/</url>  
            <layout>default</layout>  
        </repository>  
    </repositories> 
    
    <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
    </properties>  
    
    <dependencies><!-- 這個元素描述了所有與當前專案相關的依賴 -->  
        <!-- junit -->  
        <dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>4.11</version>  
            <scope>test</scope>  
        </dependency>  
          
        <!-- servlet -->  
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>servlet-api</artifactId>  
            <version>3.0-alpha-1</version>  
            <scope>provided</scope>  
        </dependency>  
          
        <!-- log4j -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
        </dependency>  
          
        <!-- jstl -->  
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
        </dependency>  
        <dependency>  
            <groupId>javax.servlet.jsp</groupId>  
            <artifactId>jsp-api</artifactId>  
            <version>2.2.1-b03</version>  
            <scope>provided</scope>  
        </dependency>  
          
        <!-- 檔案上傳 -->  
        <dependency>  
            <groupId>commons-fileupload</groupId>  
            <artifactId>commons-fileupload</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
          
        <!-- fastJson json陣列有關的 -->  
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>fastjson</artifactId>  
            <version>1.1.26</version>  
        </dependency>  
          
        <!-- 使用 Jackson 把 Java 物件轉換成 JSON 字串 -->  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.11</version>  
        </dependency>  
          

        
        <!-- oracle 資料庫驅動 -->
        <dependency>
		<groupId>com.oracle</groupId>
		<artifactId>ojdbc14</artifactId>
		<version>10.2.0.2.0</version>
	</dependency>
  
        <!-- druid -->  
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>druid</artifactId>  
            <version>0.2.9</version>  
        </dependency>  
          
        <!-- aspectjweaver.jar這是Spring AOP所要用到的包 -->  
        <dependency>  
            <groupId>org.aspectj</groupId>  
            <artifactId>aspectjweaver</artifactId>  
            <version>1.7.1</version>  
        </dependency>  
          
        <!-- hibernate4 -->  
        <dependency>  
            <groupId>org.hibernate</groupId>  
            <artifactId>hibernate-core</artifactId>  
            <version>4.2.5.Final</version>  
        </dependency>       
        <dependency>  
            <groupId>org.hibernate</groupId>  
            <artifactId>hibernate-entitymanager</artifactId>  
            <version>4.2.5.Final</version>  
        </dependency>  
        <dependency>  
            <groupId>org.hibernate</groupId>  
            <artifactId>hibernate-ehcache</artifactId>  
            <version>4.2.5.Final</version>  
        </dependency>  
        <dependency>  
            <groupId>org.hibernate.javax.persistence</groupId>  
            <artifactId>hibernate-jpa-2.0-api</artifactId>  
            <version>1.0.1.Final</version>  
        </dependency>  
          
        <!-- spring mvc -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
          
        <!-- spring3 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>       
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-beans</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-expression</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-orm</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version>3.2.0.RELEASE</version>  
        </dependency>  
          
    </dependencies>  

  <build>
 	 <plugins>
  		 <plugin>  
			    <groupId>org.mortbay.jetty</groupId>  
			    <artifactId>maven-jetty-plugin</artifactId>  
			    <version>6.1.26</version>  
			    <configuration>               
			        <scanIntervalSeconds>3</scanIntervalSeconds>  
			        <connectors>  
			            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">  
			                <port>8090</port>  
			            </connector>  
			        </connectors>                     
			        <scanTargetPatterns>  
			            <scanTargetPattern>  
			                <directory>src/main/webapp/WEB-INF</directory>  
			                <excludes>  
			                    <exclude>**/*.jsp</exclude>  
			                </excludes>  
			                <includes>  
			                    <include>**/*.properties</include>  
			                    <include>**/*.xml</include>  
			                </includes>  
			            </scanTargetPattern>  
			        </scanTargetPatterns>  
			    </configuration>  
			</plugin>
		</plugins>
    <finalName>sms</finalName>
  </build>
</project>

五、檔案配置 

配置檔案都放在 src/main/resouces 下面

config.properties

#屬性檔案  
  
#Oracle 的配置  
hibernate.dialect=org.hibernate.dialect.OracleDialect
driverClassName=oracle.jdbc.driver.OracleDriver
validationQuery=SELECT 1 FROM DUAL
jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
jdbc_username=system
jdbc_password=Oracle123

 
#SQLServer 的配置  
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect  
#driverClassName=net.sourceforge.jtds.jdbc.Driver  
#validationQuery=SELECT 1  
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy  
#jdbc_username=  
#jdbc_password=  
  
#Derby 的配置  
#hibernate.dialect=org.hibernate.dialect.DerbyDialect  
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver  
#validationQuery=SELECT 1  
#jdbc_url=jdbc:derby:sy;create=true  
#jdbc_username=  
#jdbc_password=  
  
#MySQL 的配置  
#hibernate.dialect=org.hibernate.dialect.MySQLDialect  
#driverClassName=com.mysql.jdbc.Driver  
#validationQuery=SELECT 1  
#jdbc_url=jdbc:mysql://localhost:3306/sshf?useUnicode=true&characterEncoding=utf-8  
#jdbc_username=root  
#jdbc_password=  

hibernate.properties
hibernate.hbm2ddl.auto=update 
hibernate.show_sql=true
hibernate.format_sql=true
sessionInfoName=sessionInfo  
uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid 
uploadDirectory=attached

log4j.properties

log4j.rootLogger=INFO,A1,R  
  
log4j.appender.A1=org.apache.log4j.ConsoleAppender  
log4j.appender.A1.Target=System.out  
log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n  
  
log4j.appender.R=org.apache.log4j.RollingFileAppender   
log4j.appender.R.File=sshf.log  
log4j.appender.R.MaxFileSize=10MB  
log4j.appender.R.Threshold=ALL  
log4j.appender.R.layout=org.apache.log4j.PatternLayout  
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n  
spring-hibernate.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="  
http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-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  
">  
  
    <!-- JNDI(通過Tomcat)方式配置資料來源 -->  
    <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->  
      
      
    <!-- 配置資料來源 -->  
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">  
        <property name="url" value="${jdbc_url}" />  
        <property name="username" value="${jdbc_username}" />  
        <property name="password" value="${jdbc_password}" />  
  
        <!-- 初始化連線大小 -->  
        <property name="initialSize" value="0" />  
        <!-- 連線池最大使用連線數量 -->  
        <property name="maxActive" value="20" />  
        <!-- 連線池最大空閒 -->  
        <property name="maxIdle" value="20" />  
        <!-- 連線池最小空閒 -->  
        <property name="minIdle" value="0" />  
        <!-- 獲取連線最大等待時間 -->  
        <property name="maxWait" value="60000" />  
  
        <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->  
  
        <property name="validationQuery" value="${validationQuery}" />  
        <property name="testOnBorrow" value="false" />  
        <property name="testOnReturn" value="false" />  
        <property name="testWhileIdle" value="true" />  
  
        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->  
        <property name="timeBetweenEvictionRunsMillis" value="60000" />  
        <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->  
        <property name="minEvictableIdleTimeMillis" value="25200000" />  
  
        <!-- 開啟removeAbandoned功能 -->  
        <property name="removeAbandoned" value="true" />  
        <!-- 1800秒,也就是30分鐘 -->  
        <property name="removeAbandonedTimeout" value="1800" />  
        <!-- 關閉abanded連線時輸出錯誤日誌 -->  
        <property name="logAbandoned" value="true" />  
  
        <!-- 監控資料庫 -->  
        <!-- <property name="filters" value="stat" /> -->  
        <property name="filters" value="mergeStat" />  
    </bean>  
  
    <!-- 配置hibernate session工廠 -->  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>  
            </props>  
        </property>  
  
        <!-- 自動掃描註解方式配置的hibernate類檔案 -->  
        <property name="packagesToScan">  
            <list>  
                <value>com.sms.model</value>  
            </list>  
        </property>  
    </bean>  
  
    <!-- 配置事務管理器 -->  
    <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory"></property>  
    </bean>  
  
    <!-- 註解方式配置事物 -->  
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->  
  
    <!-- 攔截器方式配置事物 -->  
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
            <tx:method name="add*" />  
            <tx:method name="save*" />  
            <tx:method name="update*" />  
            <tx:method name="modify*" />  
            <tx:method name="edit*" />  
            <tx:method name="delete*" />  
            <tx:method name="remove*" />  
            <tx:method name="repair" />  
            <tx:method name="deleteAndRepair" />  
  
            <tx:method name="get*" propagation="SUPPORTS" />  
            <tx:method name="find*" propagation="SUPPORTS" />  
            <tx:method name="load*" propagation="SUPPORTS" />  
            <tx:method name="search*" propagation="SUPPORTS" />  
            <tx:method name="datagrid*" propagation="SUPPORTS" />  
  
            <tx:method name="*" propagation="SUPPORTS" />  
        </tx:attributes>  
    </tx:advice>  
    <aop:config>  
        <aop:pointcut id="transactionPointcut" expression="execution(* com.sms.service..*impl.*(..))" />  
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />  
    </aop:config>  
  
  
</beans>

spring-mvc.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:p="http://www.springframework.org/schema/p"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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.1.xsd    
      http://www.springframework.org/schema/mvc    
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
    <!-- 註解掃描包 -->  
    <context:component-scan base-package="com.sms.controller" />  
    <!-- 開啟mvc註解 -->  
    <mvc:annotation-driven />  
  
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean>  
</beans>  

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" xmlns:context="http://www.springframework.org/schema/context" 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  
">  
  
    <!-- 引入屬性檔案 -->  
    <context:property-placeholder location="classpath:config.properties,classpath:hibernate.properties" />  
  
    <!-- 自動掃描dao和service包(自動注入) -->  
    <context:component-scan base-package="com.sms.dao,com.sms.service" />  
  
</beans>

配置檔案目錄


web.xml 配置

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    version="3.0">  
    <display-name></display-name>  
    <!-- spring hibernate -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>  
    </context-param>  
    <!-- openSessionInView配置 -->  
    <filter>  
        <filter-name>openSessionInViewFilter</filter-name>  
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
        <init-param>  
            <param-name>singleSession</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <!--spring mvc 配置 -->  
    <servlet>  
        <servlet-name>sms</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
  
    <servlet-mapping>  
        <servlet-name>sms</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
  
  
    <!-- encodeing -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <!-- encoding filter for jsp page -->  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
  
  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
  
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>  

六、實現一個學生表的增刪改查

新建 controller dao model  service  service.impl包


Student.java

package com.sms.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.GenericGenerator;

@javax.persistence.Entity
@javax.persistence.Table(name = "STUDENT")
@AccessType("field")
public class Student  implements Serializable{

private static final long serialVersionUID = 1L;

/**
 *
 */
@Id
@Column(name = "ID", length = 32)
@GeneratedValue(generator = "uuid")  
@GenericGenerator(name = "uuid", strategy = "uuid")  
private String id;
/**
 *
 */
@Column(name = "NAME", length = 10)
private String name;
/**
 *
 */
public String getId(){
	return this.id;
}
/**
 *
 *@param id
 */
public void setId(String id){
	this.id=id;
}

/**
 *
 */
public String getName(){
	return this.name;
}
/**
 *
 *@param name
 */
public void setName(String name){
	this.name=name;
}

}

StudentDao.java

package com.sms.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sms.model.Student;

@Repository
public class StudentDao {
	
	@Autowired
	 private SessionFactory sessionFactory;  
	
	/**
	 * 
	 * 獲取studentList
	 */
	public List<Student> getstudentList(){
		
		Session session = sessionFactory.openSession();
		String hql = "from Student";      
		Query query = session.createQuery(hql);      
		List<Student> studentList = query.list(); 
		session.close();
		return studentList;
	}
	
	
	/**
	 * 
	 * 根據id刪除學生
	 */
	public void deleteStudent(String sid){
		Session session = sessionFactory.openSession();
		String hql = "delete from Student where id = ? ";
		Query query =  session.createQuery(hql);
		query.setString(0, sid);
		query.executeUpdate();
		session.close();
		
	}
	
	/**
	 * 
	 * 儲存學生
	 */
	@Transactional
	public void saveOrUpdate(Student student,String sid){
		
		if(!"".equals(sid)&&null!=sid){
			student.setId(sid);
		}
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(student);
		tx.commit();
	}
	
	/**
	 * 獲取學生
	 */
	public Student getStudent(String sid){
		Session session = sessionFactory.openSession();
		return (Student) session.get(Student.class, sid);
	}
	
	
	
}


IStudentService.java

package com.sms.service.impl;

import java.util.List;

import com.sms.model.Student;

public interface IStudentService {
	
	public List<Student> getStudentList();
	
	public void deleteStudent(String sid);
	
	public void saveOrUpdateStudent(Student student,String sid);
	
	public Student getStudent(String sid);
	

}


StudentService.java

package com.sms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sms.dao.StudentDao;
import com.sms.model.Student;
import com.sms.service.impl.IStudentService;

@Repository 
public class StudentService implements IStudentService{
     
	@Autowired
	private StudentDao studentDao;
	
	@Override
	public List<Student> getStudentList() {
	
		
		return studentDao.getstudentList();
	}

	@Override
	public void deleteStudent(String sid) {
	
		studentDao.deleteStudent(sid);
	}

	@Override
	public Student getStudent(String sid) {
		
		return studentDao.getStudent(sid);
	}

	@Override
	public void saveOrUpdateStudent(Student student,String sid) {
	
		studentDao.saveOrUpdate(student,sid);
	}

}


StudentController.java

package com.sms.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sms.model.Student;
import com.sms.service.StudentService;

@Controller
public class StudentController {
	
	@Autowired
	private StudentService service;
	
	/**
	 * 獲取學生列表
	 */
	@RequestMapping("/getstudentList.do")
	public String getStudentList(Model model){
		
		
		List<Student> list = service.getStudentList();
		model.addAttribute("slist", list);
		
		return "studentList";
	}
	
	/**
	 * 根據id刪除學生
	 */
	@RequestMapping("/deleteStudent.do")
	public String deleteStudent(String sid){
		
		service.deleteStudent(sid);
		return "redirect:/getstudentList.do";
	}
	
	/**
	 * 
	 * 跳轉到新增 編輯學生介面
	 */
	@RequestMapping("/addOreditStudent.do")
	public String toAddStudentPage(String sid,Model model){
		
		Student student = new Student();
		
		if(!"".equals(sid)&&null!=sid){
			student =  service.getStudent(sid);
		}else{
			student = null;
		}
		model.addAttribute("student", student);
		return "addStudentPage";
	}
	
	/**
	 *儲存學生 
	 */
	@RequestMapping("/saveOrupdateStudent.do")
	public String saveOrUpdateStudent(Student student,String sid){
		
		service.saveOrUpdateStudent(student,sid);
		return "redirect:/getstudentList.do";
	}
}


七、前臺介面


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<a href="getstudentList.do">學生列表</a>

</body>
</html>


studentList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
td{
 border: solid 1px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<span><a href="/sms/addOreditStudent.do">新增</a></span>
<table style="border:  solid 1px"> 
<c:forEach var="slist" items="${slist}">
	<tr>
	<td>${slist.id}</td>
	<td>${slist.name}</td>
	<td> <a href="/sms/addOreditStudent.do?sid=${slist.id}">編輯</a></td>
	<td> <a href="/sms/deleteStudent.do?sid=${slist.id}">刪除</a></td>
	</tr>
</c:forEach>
</table>
</center>
</body>
</html>


addStudentPage.jsp

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/sms/saveOrupdateStudent.do?sid=${student.id}" method="post">
	學生姓名: <input type="text" name="name" value="${student.name}"/>
	<input type="submit" value="儲存">
</form>
</body>
</html>

八、完成

首頁:


學生列表


刪除



新增



編輯



九、剛到企業裡實習 公司的框架都有很好的封裝 很多配置檔案都沒有好好去看 希望大家多瞭解配置 不要一味的寫程式碼