SSH+Oracle的整合(SSH與Oracle整合坑巨多)


這里用SSH+Oracle做一個倉庫管理系統,其中包含了查詢、條件查詢、刪除、批量刪除、修改、添加的功能。值得注意的是,Oracle與其它數據庫存在很多不同之處,所以SSH和Oracle整合的時候小細節處理稍有不慎,就要花費大量時間去排查,親身體會!

下面進入正文 ↓↓↓↓

Oracle數據庫:

goods.sql

注意:創建表的時候,無論表名大寫小寫,創建完成時都會默認設置成大寫。

--創建倉庫表
create table goods
(
       Gno number not null primary key, --編號
       gname varchar2(500) not null,  --物質名稱
       gtype varchar2(20) not null,   --物質類型
       Gnumber number not null check (Gnumber > 0),       --物質數量
       Gcompany varchar2(500) not null, --生產商
       Gcreatetime date default sysdate,       --生產日期
       Uintime date default sysdate   --入庫時間
);
drop table goods;
--創建自增序列
create sequence goods_id
increment by 1  --增量為1
start with 1    --從1開始生成序列
nomaxvalue;      --沒有最大值

--插入數據
insert into goods(Gno,gname,gtype,gnumber,gcompany) values(goods_id.nextval,'康師傅方便面','食品','150000','康師傅食品有限公司');
insert into goods(Gno,gname,gtype,gnumber,gcompany) values(goods_id.nextval,'康師傅礦泉水','飲用水','150000','康師傅食品有限公司');
insert into goods(Gno,gname,gtype,gnumber,gcompany) values(goods_id.nextval,'康師傅辣條','食品','150000','康師傅食品有限公司');
insert into goods(Gno,gname,gtype,gnumber,gcompany) values(goods_id.nextval,'康師傅可樂','食品','150000','康師傅食品有限公司');
insert into goods(Gno,gname,gtype,gnumber,gcompany) values(goods_id.nextval,'康師傅面包','食品','150000','康師傅食品有限公司');

select * from goods;

select * from goods order by gcreatetime desc;

commit;

 

SSH:

包結構:

 

idea中數據庫插件配置:

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hsl</groupId>
    <artifactId>Goods</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!--spring-->
        <!-- 這個依賴可以讓spring容器有bean管理,依賴注入,基本的切面配置功能,但不支持切點表達式以及其解析-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- 讓spring支持切點表達式功能-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!-- 這個依賴是spring專門用來與其他持久層框架進行整合用的一個依賴里面有LocalSessionFactoryBean類型-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- 此依賴有事務方面的通知,事務管理器等 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--hibernate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.10.Final</version>
        </dependency>

        <!--struts-->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.5.12</version>
        </dependency>

        <!--oracle-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>


        <!-- 這是dbcp連接池依賴,完全可以換別的連接池組件-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.2.0</version>
        </dependency>

        <!--<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>-->

    </dependencies>

    <build>
        <plugins>
            <!--用於設定源代碼文件的編碼,以及項目代碼運行的目標jdk版本為1.8 -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- 指定項目中web資源的根目錄,用於maven打包時把此目錄的所有內容拷貝到war中-->
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <warSourceDirectory>web</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

Goods.java

package entity;

import java.util.Date;

public class Goods {

    private int Gno ; //編號
    private String gname ;  //物質名稱
    private String gtype ;  //物質類型
    private int Gnumber ;  //物質數量
    private String Gcompany ;  //生產商
    private Date Gcreatetime ;  //生產日期
    private Date Uintime ;  //入庫時間

    public int getGno() {
        return Gno;
    }

    public void setGno(int gno) {
        Gno = gno;
    }

    public String getGname() {
        return gname;
    }

    public void setGname(String gname) {
        this.gname = gname;
    }

    public String getGtype() {
        return gtype;
    }

    public void setGtype(String gtype) {
        this.gtype = gtype;
    }

    public int getGnumber() {
        return Gnumber;
    }

    public void setGnumber(int gnumber) {
        Gnumber = gnumber;
    }

    public String getGcompany() {
        return Gcompany;
    }

    public void setGcompany(String gcompany) {
        Gcompany = gcompany;
    }

    public Date getGcreatetime() {
        return Gcreatetime;
    }

    public void setGcreatetime(Date gcreatetime) {
        Gcreatetime = gcreatetime;
    }

    public Date getUintime() {
        return Uintime;
    }

    public void setUintime(Date uintime) {
        Uintime = uintime;
    }
}

 

GoodsDao.java

package dao;

import entity.Goods;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import java.util.Date;
import java.util.List;

public class GoodsDao {
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    //查詢全部
    public List<Goods> getAll(){
        Session session = sessionFactory.getCurrentSession();
        String sql = "from Goods as g order by g.Gcreatetime desc";
        return session.createQuery(sql).list();
    }

    //增加
    public void addGoods(Goods goods){
        Session session = sessionFactory.getCurrentSession();
        session.save(goods);
    }

    //刪除
    public void delete(int Gno){
        Session session = sessionFactory.getCurrentSession();
        session.delete(session.get(Goods.class,Gno));
    }

    //根據編號查詢
    public Goods getById(int Gno){
        Session session = sessionFactory.getCurrentSession();
        return session.get(Goods.class,Gno);
    }

    //修改
    public void update(Goods goods){
        Session session = sessionFactory.getCurrentSession();
        session.update(goods);
    }

    //按條件查詢
    public List<Goods> getByTerm(String gname, Date firstTime,Date lastTime){
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Goods g where g.gname like :gname and g.Gcreatetime between :firstTime and :lastTime";
        Query query = session.createQuery(hql);
        query.setParameter("gname","%"+gname+"%");
        query.setParameter("firstTime",firstTime);
        query.setParameter("lastTime",lastTime);
        return query.list();

    }

    //批量刪除
    public void deleteAll(String[] Gno){
        Session session = sessionFactory.getCurrentSession();
        for(int i=0;i<Gno.length;i++){
            Goods goods = this.getById(Integer.parseInt(Gno[i]));
            session.delete(goods);
        }
    }

}

 

 GoodsService.java

package service;

import dao.GoodsDao;
import entity.Goods;

import java.util.Date;
import java.util.List;

public class GoodsService {
    private GoodsDao goodsDao;

    public GoodsDao getGoodsDao() {
        return goodsDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    public List<Goods> getAll(){
        return goodsDao.getAll();
    }

    public void addGoods(Goods goods){
        goodsDao.addGoods(goods);
    }

    public void delete(int Gno){
        goodsDao.delete(Gno);
    }

    public Goods getById(int Gno){
        return goodsDao.getById(Gno);
    }

    public void update(Goods goods){
        goodsDao.update(goods);
    }

    public List<Goods> getByTerm(String gname, Date firstTime, Date lastTime){
        return goodsDao.getByTerm(gname,firstTime,lastTime);
    }

    public void deleteAll(String[] Gno){
        goodsDao.deleteAll(Gno);
    }
}

 

GoodsController.java

package controller;

import com.opensymphony.xwork2.ActionContext;
import entity.Goods;
import service.GoodsService;

import java.util.Date;
import java.util.List;

public class GoodsController {
    private GoodsService goodsService;

    private Goods goods;

    private Date firstTime;
    private Date lastTime;
    private String Gnos;

    public String getGnos() {
        return Gnos;
    }

    public void setGnos(String gnos) {
        Gnos = gnos;
    }

    public Date getFirstTime() {
        return firstTime;
    }

    public void setFirstTime(Date firstTime) {
        this.firstTime = firstTime;
    }

    public Date getLastTime() {
        return lastTime;
    }

    public void setLastTime(Date lastTime) {
        this.lastTime = lastTime;
    }

    public Goods getGoods() {
        return goods;
    }

    public void setGoods(Goods goods) {
        this.goods = goods;
    }

    public GoodsService getGoodsService() {
        return goodsService;
    }

    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    //查詢全部
    public String list(){
        List<Goods> goods = goodsService.getAll();
        ActionContext.getContext().put("goods",goods);
        return "list";
    }
    //添加商品
    public String add(){
        goodsService.addGoods(goods);
        return "success";
    }
    //刪除商品
    public String delete(){
        goodsService.delete(goods.getGno());
        return "success";
    }
    //批量刪除
    public String deleteAll(){
        System.out.println(Gnos);
        String[] gnos = Gnos.split(",");
        goodsService.deleteAll(gnos);
        return "success";
    }
    //查詢要修改的商品
    public String edit(){
        Goods goods1 = goodsService.getById(goods.getGno());
        ActionContext.getContext().put("goods1",goods1);
        return "edit";
    }
    //修改商品
    public String update(){
        goodsService.update(goods);
        return "success";
    }

    //按條件查詢
    public String getByTerm(){
        List<Goods> goods2 = goodsService.getByTerm(goods.getGname(),firstTime,lastTime);
        ActionContext.getContext().put("goods",goods2);
        return "list";
    }
}

 

Goods.hbm.xml

注意:

  1.table需要寫全稱。

  2.dynamic-insert和dynamic-update表示是否啟動默認值,如果沒有設置true則數據庫中默認的字段會為空。

  3.主鍵生成策略為increment,其它無效,不知道為什么。

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="entity">

    <class name="entity.Goods" table="SCOTT.GOODS" dynamic-insert="true" dynamic-update="true" >
        <id name="Gno" column="Gno">
            <generator class="increment">
                <!--<param name="sequence">GOODS_ID</param>-->
            </generator>
        </id>
        <property name="gname" column="gname"/>
        <property name="gtype" column="gtype"/>
        <property name="Gnumber" column="Gnumber"/>
        <property name="Gcompany" column="Gcompany"/>
        <property name="Gcreatetime" column="Gcreatetime"/>
        <property name="uintime" column="uintime"/>
    </class>
</hibernate-mapping>

 

db.properties

url=jdbc:oracle:thin:@localhost:1521:orcl
driverclass=oracle.jdbc.driver.OracleDriver
username=SCOTT
password=tiger

 

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"
       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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:property-placeholder location="classpath:db.properties" local-override="true"/>
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="url" value="${url}"></property>
        <property name="driverClassName" value="${driverclass}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        
        <!--<property name="initialSize" value="5"></property>
        <property name="maxIdle" value="10"></property>
        <property name="maxTotal" value="10"></property>-->
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" destroy-method="destroy">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mappingLocations">
            <list>
                <value>classpath:Goods.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</prop>
            </props>
        </property>
    </bean>

    <bean id="GoodsDao" class="dao.GoodsDao">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="delete*"/>
            <tx:method name="update*"/>
            <tx:method name="add*"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="allServices"
                      expression="execution(public * service.*.*(..))"/>
        <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="allServices"/>
    </aop:config>

    <bean id="goodsService" class="service.GoodsService">
        <property name="goodsDao" ref="GoodsDao"/>
    </bean>

    <bean id="goods" class="entity.Goods"/>

    <bean id="controller" class="controller.GoodsController">
        <property name="goodsService" ref="goodsService"/>
        <property name="goods" ref="goods"/>
    </bean>


</beans>

 

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <package name="goods" extends="struts-default">
        <global-allowed-methods>list,add,delete,edit,update,getByTerm,deleteAll</global-allowed-methods>
        <action name="goods*" class="controller" method="{1}">
            <result name="list">index.jsp</result>
            <result name="success" type="redirectAction">goodslist</result>
            <result name="edit">edit.jsp</result>
        </action>
    </package>
    
</struts>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/4/5
  Time: 16:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>商品管理系統</title>
  </head>
  <body>
  <h1>商品管理系統</h1>
  <table border="1" width="100%">
    <tr>
      <th colspan="9">
        <form action="goodsgetByTerm" method="post">
          商品名:<input type="text" name="goods.gname" />
          生產日期:<input type="date" name="firstTime"/>-<input type="date" name="lastTime" />
          <input type="submit" value="查詢" />
        </form>
      </th>
    </tr>
    <tr>
        <th>全選<input type="checkbox" onclick="" name="checkAll" /></th>
        <th>編號</th>
        <th>物資名稱</th>
        <th>類型</th>
        <th>數量(件)</th>
        <th>生產商</th>
        <th>生產日期</th>
        <th>入庫日期</th>
        <th>操作</th>
    </tr>
    <s:iterator value="#goods" var="g">
        <tr>
            <td><input type="checkbox" name="check" value="<s:property value="#g.Gno"/>" /></td>
            <td><s:property value="#g.Gno"/> </td>
            <td><s:property value="#g.gname"/> </td>
            <td><s:property value="#g.gtype"/> </td>
            <td><s:property value="#g.Gnumber"/> </td>
            <td><s:property value="#g.Gcompany"/> </td>
            <td><s:property value="#g.Gcreatetime"/> </td>
            <td><s:property value="#g.Uintime"/> </td>
            <td><a href="goodsedit?goods.Gno=<s:property value="#g.Gno" />">修改</a> | <a href="goodsdelete?goods.Gno=<s:property value="#g.Gno" />">刪除</a></td>
        </tr>
    </s:iterator>
    <tr>
         <th colspan="9">
             <input type="button" id="deleteAll" value="批量刪除" />
         </th>
    </tr>
  </table>
  <a href="add.jsp">增加商品</a>

  <script type="text/javascript" src="jquery-1.12.4.js"></script>
  <script>
      $(function(){
          //全選、反選
          $('input[name="checkAll"]').click(function(){
              if($(this).is(':checked')){
                  $('input[name="check"]').each(function () {
                      $(this).prop("checked",true);
                  });
              } else {
                  $('input[name="check"]').each(function () {
                      $(this).prop("checked",false);
                  });
              }
          });

          //批量刪除
          $("#deleteAll").click(function(){
              var Gnos = new Array();
              $("input[name='check']:checked").each(function() {
                  Gnos.push($(this).val());
              });
              if(Gnos.length==0){
                  alert("沒有選中");
                  return;
              }
              $.ajax({
                  url:'/goodsdeleteAll',
                  type:'post',
                  data:{'Gnos':Gnos.toString()},
                  success:function (data) {
                      window.location.reload();
                  }
              });
          });

      });

  </script>
  </body>
</html>

 

add.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/4/6
  Time: 15:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>增加商品</title>
</head>
<body>
    <h1>添加商品</h1>
    <form action="goodsadd" method="post">
        <p>
            <label>名稱:</label>
            <input type="text" name="goods.gname" />
        </p>
        <p>
            <label>類型:</label>
            <input type="text" name="goods.gtype" />
        </p>
        <p>
            <label>數量:</label>
            <input type="number" name="goods.Gnumber" />
        </p>
        <p>
            <label>生產商:</label>
            <input type="text" name="goods.Gcompany" />
        </p>
        <p>
            <input type="submit" value="提交" />
        </p>
    </form>
</body>
</html>

 

edit.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/4/6
  Time: 15:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改商品</title>
</head>
<body>
    <h1>修改商品</h1>
    <form action="goodsupdate" method="post">
        <p>
            <label>名稱:</label>
            <input type="text" value="<s:property value="#goods1.gname"/>" name="goods.gname" />
        </p>
        <p>
            <label>類型:</label>
            <input type="text" value="<s:property value="#goods1.gtype"/>" name="goods.gtype" />
        </p>
        <p>
            <label>數量:</label>
            <input type="text" value="<s:property value="#goods1.Gnumber"/>" name="goods.Gnumber" />
        </p>
        <p>
            <label>生產商:</label>
            <input type="text" value="<s:property value="#goods1.Gcompany"/>" name="goods.Gcompany" />
        </p>
        <p>
            <label>生產日期:</label>
            <input type="date" value="<s:property value="#goods1.Gcreatetime"/>" name="goods.Gcreatetime" />
        </p>
        <p>
            <input type="hidden" value="<s:property value="#goods1.Gno"/>" name="goods.Gno" />
            <input type="hidden" value="<s:property value="#goods1.uintime"/>" name="goods.uintime" />
            <input type="submit" value="提交" />
        </p>
    </form>
</body>
</html>

 

效果圖:

git地址:https://git.coding.net/h951995489/Goods_SSH_Oracle.git

The end!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM