小规模应用的开发

阅读更多

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




    
        org.postgresql.Driver
        okada
        jdbc:postgresql://localhost:5432/BookStore
        okada
        org.hibernate.dialect.PostgreSQLDialect
    

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 items = null;
	private String[] selecteditems = null;
	
	
	public AddToCartItems(){
		items = BookDB.getBookListAll();
	}
	
	public List getItems(){
		return( this.items );
	}
	
	public void setItems( List 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 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 cart = (List) 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 getBookListAll(){
		Session session = BookDB.getHibernateSession();
		
		List booklist = (List)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 TOrderDetails = new HashSet(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 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 getTOrderDetails() {
		return this.TOrderDetails;
	}

	public void setTOrderDetails(Set 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 TOrders = new HashSet(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 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 getTOrders() {
		return this.TOrders;
	}

	public void setTOrders(Set 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 TOrderDetails = new HashSet(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 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 getTOrderDetails() {
		return this.TOrderDetails;
	}

	public void setTOrderDetails(Set 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" %>








	

	

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" %>







	

購入商品



以下が購入する商品と合計です。
<% List listCheckedBook = (List)session.getAttribute( "CART" ); if( listCheckedBook != null ){ for( String iterBookISBN : listCheckedBook ){ TBook book = (TBook)BookDB.findBookByISBN( iterBookISBN ); %> <% } } %>
<%= book.getTitle() %> <%= book.getAuthor() %>
<%= book.getPublisher() %> <%= book.getPrice() %>


合計: <%= request.getAttribute( "TOTAL" ) %> 円

WebContent\WEB-INF:

hibernate.cfg.xml




    
        false
        org.postgresql.Driver
        okada
        jdbc:postgresql://localhost:5432/BookStore
        okada
        org.hibernate.dialect.PostgreSQLDialect
        
        
        
        
    

struts-config.xml



	

	
		
	
	
		
			
			
		
	
    
	

web.xml



	Chap10

	
        action
        org.apache.struts.action.ActionServlet       
        
            config
            /WEB-INF/struts-config.xml
        
        1
    

    
                                                                   
        action
        *.do
                                                                  

    
    
        BookStore.jsp
    

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

你可能感兴趣的:(Hibernate,Struts,出版,Servlet,Bean)