init:
initdb
dropdb BookStore
createdb -U okada BookStore
init-table
drop sequence hibernate_sequence;
drop table t_order_detail;
drop table t_order;
drop table t_book;
drop table t_customer;
create sequence hibernate_sequence;
create table t_customer(
id integer default nextval( 'hibernate_sequence' )
primary key unique not null,
uid text not null unique,
passwordmd5 text not null,
name text not null,
email text not null );
create table t_book(
id integer default nextval( 'hibernate_sequence' )
primary key unique not null,
isbn text not null unique,
title text not null,
author text not null,
publisher text not null,
price integer not null );
create table t_order(
id integer default nextval( 'hibernate_sequence' )
primary key unique not null,
customer_id_fk integer not null
constraint order_customer_id_constraint
references t_customer(id),
orderday timestamp with time zone not null );
create table t_order_detail(
id integer default nextval( 'hibernate_sequence' )
primary key unique not null,
order_id_fk integer not null
constraint detail_order_id_constraint
references t_order(id),
book_id_fk integer not null
constraint defail_book_id_constraint
references t_book(id) );
init-data
delete from t_book;
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1234-5678-1', '坊ちゃん', '夏目漱石','A出版社', 450 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1234-5679-2', '三四郎', '夏目漱石','A出版社', 480 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1234-5670-1', '走れメロス', '太宰治','A出版社', 580 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1234-5670-2', '富嶽百景', '太宰治','A出版社', 430 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1230-1234-1', '銀河鉄道の夜', '宮沢賢治','B出版社', 650 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1230-1234-2', 'セロ弾きのゴーシュ', '宮沢賢治','B出版社', 380 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1230-2345-1', '伊豆の踊り子', '川端康成','B出版社', 780 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-1230-2345-2', '雪国', '川端康成','B出版社', 700 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-3456-1111-1', '羅生門', '芥川龍之介','C出版社', 580 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-3456-1111-2', '蜘蛛の糸', '芥川龍之介','C出版社', 880 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-3456-2222-1', '大つごもり', '樋口一葉','C出版社', 550 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-3456-2222-2', 'たけくらべ', '樋口一葉','C出版社', 660 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-7980-1256-4', 'Javaフレームワーク入門', '掌田津耶乃','秀和システム', 2940 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-7980-1225-4', 'Eclipse3.1によるJavaアプリケーション開発', '水島和憲','秀和システム', 2940 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-7980-1209-2', 'はじめてのJSP&サーブレットプログラミング', 'アイティーブースト','秀和システム', 2835 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-7980-1187-8', 'Eclipse3+VisualEditorによるJavaプログラミング', 'プロジェクトウィルカ','秀和システム', 2625 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-7980-1086-3', 'UNIXコマンドリファレンス', '松本光春','秀和システム', 1365 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-7980-0680-7', '世界でいちばん簡単なUNIXのe本', '堀江幸生、山内敏昭','秀和システム', 1365 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-6543-1289-1', '世界の中心でUNIXを叫ぶ', '木村次郎','Z出版社', 2280 );
insert into t_book ( isbn, title, author, publisher, price ) values(
'4-6543-2367-1', '今UNIXにゆきます', '鈴木三郎','Z出版社', 3800 );
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">org.postgresql.Driver</property> <property name="hibernate.connection.password">okada</property> <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/BookStore</property> <property name="hibernate.connection.username">okada</property> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> </session-factory> </hibernate-configuration>
src\bookstore\action:
AddToCartItems.java
package bookstore.action;
import java.util.List;
import org.apache.struts.action.ActionForm;
import bookstore.db.BookDB;
import bookstore.pbean.TBook;
public class AddToCartItems extends ActionForm{
private List<TBook> items = null;
private String[] selecteditems = null;
public AddToCartItems(){
items = BookDB.getBookListAll();
}
public List<TBook> getItems(){
return( this.items );
}
public void setItems( List<TBook> inItems ){
this.items = inItems;
}
public String[] getSelecteditems(){
return( this.selecteditems );
}
public void setSelecteditems( String[] inSelecteditems ){
this.selecteditems = inSelecteditems;
}
}
CartAction.java
package bookstore.action;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;
import bookstore.db.BookDB;
public class CartAction extends DispatchAction{
public ActionForward addToCart( ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res ){
HttpSession session = req.getSession();
session.removeAttribute( "CART" );
AddToCartItems atci = (AddToCartItems)form;
List<String> cart = Arrays.asList( atci.getSelecteditems() );
session.setAttribute( "CART", cart );
return( mapping.findForward( "continue" ) );
}
public ActionForward checkout(ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res) {
HttpSession httpsession = req.getSession(false);
List<String> cart = (List<String>) httpsession.getAttribute("CART");
Session session = BookDB.getHibernateSession();
Query priceQuery = session
.createQuery("select sum( book.price ) from TBook book where book.isbn in ( :SELECTED_ITEMS )");
priceQuery.setParameterList("SELECTED_ITEMS", cart.toArray());
Long total = (Long)priceQuery.uniqueResult();
req.setAttribute("TOTAL", total);
return (mapping.findForward("tocheck"));
}
}
src\bookstore\db:
BookDB.java
package bookstore.db;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import bookstore.pbean.TBook;
public class BookDB{
private static SessionFactory sf = null;
public static List<TBook> getBookListAll(){
Session session = BookDB.getHibernateSession();
List<TBook> booklist = (List<TBook>)session.createQuery( "from TBook" ).list();
return( booklist );
}
public static TBook findBookByISBN( String inISBN ){
Session session = getHibernateSession();
if( session == null || session.isOpen() == false ){
session = getHibernateSession();
}
Query findquery = session.createQuery( "from TBook book where book.isbn like :ISBN" );
findquery.setString( "ISBN", inISBN );
TBook returnValue = (TBook)findquery.uniqueResult();
return( returnValue );
}
public static Session getHibernateSession(){
if( sf == null ){
sf = (new AnnotationConfiguration())
.configure( "../hibernate.cfg.xml" )
.buildSessionFactory();
}
return( sf.openSession() );
}
}
src\bookstore\pbean:
TBook.java
package bookstore.pbean;
// Generated 2009/01/30 0:28:39 by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import org.hibernate.annotations.GenericGenerator;
/**
* TBook generated by hbm2java
*/
@Entity
@Table(name = "t_book", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "isbn"))
public class TBook implements java.io.Serializable {
private int id;
private String isbn;
private String title;
private String author;
private String publisher;
private int price;
private Set<TOrderDetail> TOrderDetails = new HashSet<TOrderDetail>(0);
public TBook() {
}
public TBook(int id, String isbn, String title, String author,
String publisher, int price) {
this.id = id;
this.isbn = isbn;
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
}
public TBook(int id, String isbn, String title, String author,
String publisher, int price, Set<TOrderDetail> TOrderDetails) {
this.id = id;
this.isbn = isbn;
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
this.TOrderDetails = TOrderDetails;
}
@Id
@GeneratedValue(generator="hibernate_sequence")
@GenericGenerator(name="hibernate_sequence", strategy="native")
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "isbn", unique = true, nullable = false)
public String getIsbn() {
return this.isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
@Column(name = "title", nullable = false)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "author", nullable = false)
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
@Column(name = "publisher", nullable = false)
public String getPublisher() {
return this.publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
@Column(name = "price", nullable = false)
public int getPrice() {
return this.price;
}
public void setPrice(int price) {
this.price = price;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "TBook")
public Set<TOrderDetail> getTOrderDetails() {
return this.TOrderDetails;
}
public void setTOrderDetails(Set<TOrderDetail> TOrderDetails) {
this.TOrderDetails = TOrderDetails;
}
}
TCustomer.java
package bookstore.pbean;
// Generated 2009/01/30 0:28:39 by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import org.hibernate.annotations.GenericGenerator;
/**
* TCustomer generated by hbm2java
*/
@Entity
@Table(name = "t_customer", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "uid"))
public class TCustomer implements java.io.Serializable {
private int id;
private String uid;
private String passwordmd5;
private String name;
private String email;
private Set<TOrder> TOrders = new HashSet<TOrder>(0);
public TCustomer() {
}
public TCustomer(int id, String uid, String passwordmd5, String name,
String email) {
this.id = id;
this.uid = uid;
this.passwordmd5 = passwordmd5;
this.name = name;
this.email = email;
}
public TCustomer(int id, String uid, String passwordmd5, String name,
String email, Set<TOrder> TOrders) {
this.id = id;
this.uid = uid;
this.passwordmd5 = passwordmd5;
this.name = name;
this.email = email;
this.TOrders = TOrders;
}
@Id
@GeneratedValue(generator="hibernate_sequence")
@GenericGenerator(name="hibernate_sequence", strategy="native")
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "uid", unique = true, nullable = false)
public String getUid() {
return this.uid;
}
public void setUid(String uid) {
this.uid = uid;
}
@Column(name = "passwordmd5", nullable = false)
public String getPasswordmd5() {
return this.passwordmd5;
}
public void setPasswordmd5(String passwordmd5) {
this.passwordmd5 = passwordmd5;
}
@Column(name = "name", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "email", nullable = false)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "TCustomer")
public Set<TOrder> getTOrders() {
return this.TOrders;
}
public void setTOrders(Set<TOrder> TOrders) {
this.TOrders = TOrders;
}
}
TOrder.java
package bookstore.pbean;
// Generated 2009/01/30 0:28:39 by Hibernate Tools 3.2.1.GA
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.GeneratedValue;
import org.hibernate.annotations.GenericGenerator;
/**
* TOrder generated by hbm2java
*/
@Entity
@Table(name = "t_order", schema = "public")
public class TOrder implements java.io.Serializable {
private int id;
private TCustomer TCustomer;
private Date orderday;
private Set<TOrderDetail> TOrderDetails = new HashSet<TOrderDetail>(0);
public TOrder() {
}
public TOrder(int id, TCustomer TCustomer, Date orderday) {
this.id = id;
this.TCustomer = TCustomer;
this.orderday = orderday;
}
public TOrder(int id, TCustomer TCustomer, Date orderday,
Set<TOrderDetail> TOrderDetails) {
this.id = id;
this.TCustomer = TCustomer;
this.orderday = orderday;
this.TOrderDetails = TOrderDetails;
}
@Id
@GeneratedValue(generator="hibernate_sequence")
@GenericGenerator(name="hibernate_sequence", strategy="native")
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id_fk", nullable = false)
public TCustomer getTCustomer() {
return this.TCustomer;
}
public void setTCustomer(TCustomer TCustomer) {
this.TCustomer = TCustomer;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "orderday", nullable = false, length = 35)
public Date getOrderday() {
return this.orderday;
}
public void setOrderday(Date orderday) {
this.orderday = orderday;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "TOrder")
public Set<TOrderDetail> getTOrderDetails() {
return this.TOrderDetails;
}
public void setTOrderDetails(Set<TOrderDetail> TOrderDetails) {
this.TOrderDetails = TOrderDetails;
}
}
TOrderDetail.java
package bookstore.pbean;
// Generated 2009/01/30 0:28:39 by Hibernate Tools 3.2.1.GA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import org.hibernate.annotations.GenericGenerator;
/**
* TOrderDetail generated by hbm2java
*/
@Entity
@Table(name = "t_order_detail", schema = "public")
public class TOrderDetail implements java.io.Serializable {
private int id;
private TOrder TOrder;
private TBook TBook;
public TOrderDetail() {
}
public TOrderDetail(int id, TOrder TOrder, TBook TBook) {
this.id = id;
this.TOrder = TOrder;
this.TBook = TBook;
}
@Id
@GeneratedValue(generator="hibernate_sequence")
@GenericGenerator(name="hibernate_sequence", strategy="native")
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id_fk", nullable = false)
public TOrder getTOrder() {
return this.TOrder;
}
public void setTOrder(TOrder TOrder) {
this.TOrder = TOrder;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id_fk", nullable = false)
public TBook getTBook() {
return this.TBook;
}
public void setTBook(TBook TBook) {
this.TBook = TBook;
}
}
WebContent:
BookStore.jsp
<%@ page language="java" contentType="text/html;charset=Windows-31J" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> <html:html> <head> </head> <body> <html:form action="/cartAction"> <table border="1"> <logic:iterate id="item" name="AddToCartActionName" property="items"> <tr> <th rowspan="2"> <html:multibox property="selecteditems"> <bean:write name="item" property="isbn"/> </html:multibox> </th> <td colspan="3"> <bean:write name="item" property="title"/> </td> </tr> <tr> <td> <bean:write name="item" property="author" /> </td> <td> <bean:write name="item" property="publisher" /> </td> <td> <bean:write name="item" property="price" /> 円 </td> </tr> </logic:iterate> </table> <br> <html:submit property="cartaction" value="addToCart" /> <html:submit property="cartaction" value="checkout" /> </html:form> </body> </html:html>
Check.jsp
<%@ page language="java" import="java.util.Iterator" %> <%@ page import="java.util.List" %> <%@ page import="bookstore.pbean.TBook" %> <%@ page import="bookstore.db.BookDB" %> <%@ page contentType="text/html;charset=Windows-31J" %> <html> <head> </head> <body> <center> <h2>購入商品</h2> </center> <br><br> 以下が購入する商品と合計です。 <br> <table border="1"> <% List<String> listCheckedBook = (List<String>)session.getAttribute( "CART" ); if( listCheckedBook != null ){ for( String iterBookISBN : listCheckedBook ){ TBook book = (TBook)BookDB.findBookByISBN( iterBookISBN ); %> <tr> <td> <%= book.getTitle() %> </td> <td> <%= book.getAuthor() %> </td> </tr> <tr> <td> <%= book.getPublisher() %> </td> <td> <%= book.getPrice() %> </td> </tr> <% } } %> </table> <br> <br> 合計: <%= request.getAttribute( "TOTAL" ) %> 円 </body> </html>
WebContent\WEB-INF:
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.bytecode.use_reflection_optimizer">false</property> <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> <property name="hibernate.connection.password">okada</property> <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/BookStore</property> <property name="hibernate.connection.username">okada</property> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <mapping class="bookstore.pbean.TOrderDetail" /> <mapping class="bookstore.pbean.TCustomer" /> <mapping class="bookstore.pbean.TOrder" /> <mapping class="bookstore.pbean.TBook" /> </session-factory> </hibernate-configuration>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="AddToCartActionName" type="bookstore.action.AddToCartItems" /> </form-beans> <action-mappings> <action path="/cartAction" type="bookstore.action.CartAction" name="AddToCartActionName" parameter="cartaction" scope="request"> <forward name="continue" path="/BookStore.jsp" /> <forward name="tocheck" path="/Check.jsp" /> </action> </action-mappings> <message-resources parameter="resources.application"/> </struts-config>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Chap10</display-name> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- The Welcome File List --> <welcome-file-list> <welcome-file>BookStore.jsp</welcome-file> </welcome-file-list> </web-app>
WebContent\WEB-INF\lib:
antlr-2.7.6.jar
commons-beanutils-1.7.0.jar
commons-chain-1.1.jar
commons-collections-3.1.jar
commons-digester-1.8.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ejb3-persistence.jar
hibernate3.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
javassist-3.4.GA.jar
jta-1.1.jar
postgresql-8.3-603.jdbc3.jar
slf4j-api-1.5.2.jar
slf4j-jdk14-1.5.2.jar
struts-core-1.3.8.jar
struts-extras-1.3.8.jar
struts-taglib-1.3.8.jar
代码来自日本的技术图书 :http://www.shuwasystem.co.jp/products/7980html/2197.html