all gone

all gone

#

Eclipse下Hibernate入门


1.开发环境
     Eclipse 3.2+MySQL 4.0.16+Hibernate3.0
    首先应该安装好Eclipse和MySQL,此外准备好MySQL的JDBC Driver和Hibernate3.0,相关下载地址如下:
     Eclipse SDK:
        http://www.eclipse.org/downloads/index.php 
       MySQL及MySQL的JDBC Driver:
           http://www.mysql.org
       Hibernate:
          http://www.hibernate.org
       此外我还安装了Eclipse的一个Hibernate插件:
     Hibernate synchronizer
           http://hibernatesynch.sourceforge.net


       Plugin Search:
         http://eclipse-plugins.2y.net/eclipse/search.jsp 

       Hibernate synchronizer插件的安装和配置有问题请直接Google。

     在工程中其实只用到了Hibernate synchronizer插件的一部分功能,Hibernate依赖的相关jar包最好还是手动添加,因为最开始用Hibernate synchronizer添加时总是发生错误。
     将下载的Mysql driver和Hibernate包解压缩,我们需要的只是里面相关的jar,在Eclipse中新建Mysql_Driver和Hibernate两个user library,将mysql-connector-java-3.0.15-ga-bin.jar加入Mysql_Driver中,将hibernate3.jar,
,log4j-1.2.11.jar,antlr-2.7.5H3.jar,asm.jar,asm-attrs.jar,cglib-2.1.2.jar,commons-collections-2.1.1.jar,commons-logging-1.0.4.jar,dom4j-1.6.1.jar,ehcache-1.1.jar,jta.jar加入到Hibernate中。

2.开始
在Mysql中新建test数据库(Mysql其实有个空的test数据库),然后新建下面的Table

create table user (
 id int(10) not null auto_increment primary key,
 name varchar(20) not null,
 password varchar(20) not null,
 email varchar(50),
 address varchar(100)
)type=innodb;


新建Java Project,将Mysql_Driver,Hibernate两个user library添加到该工程的java build path中。

新建与数据表对应的POJO类:User和Contact

/**
 *
 * 
 */
package com.user;

/**
 * @author lzy
 *
 */
public class User{
    private Integer id;
    private String name;
    private String password;
    private Contact contact;
   

 /**
  * @return Returns the id.
  */
 public Integer getId() {
  return id;
 }
 /**
  * @param id The id to set.
  */
 public void setId(Integer id) {
  this.id = id;
 }
 /**
  * @return Returns the name.
  */
 public String getName() {
  return name;
 }
 /**
  * @param name The name to set.
  */
 public void setName(String name) {
  this.name = name;
 }
 /**
  * @return Returns the password.
  */
 public String getPassword() {
  return password;
 }
 /**
  * @param password The password to set.
  */
 public void setPassword(String password) {
  this.password = password;
 }
 /**
  * @return Returns the contact.
  */
 public Contact getContact() {
  return contact;
 }
 /**
  * @param contact The contact to set.
  */
 public void setContact(Contact contact) {
  this.contact = contact;
 }
   
   
}
/**
 *
 */
package com.user;

/**
 * @author lzy
 *
 */
public class Contact {
 private String email;
    private String address;

 /**
  * @return Returns the address.
  */
 public String getAddress() {
  return address;
 }
 /**
  * @param address The address to set.
  */
 public void setAddress(String address) {
  this.address = address;
 }
 /**
  * @return Returns the email.
  */
 public String getEmail() {
  return email;
 }
 /**
  * @param email The email to set.
  */
 public void setEmail(String email) {
  this.email = email;
 }
}

之后可以用synchronizer插件生成Hibernate配置文件和映射文件(相关过程可以参考http://www.ideagrace.com/html/doc/2005/08/01/00315.html),不过映射文件必须稍作修改。

hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory >

  <!-- local connection properties -->
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.username"></property>
  <property name="hibernate.connection.password"></property>
  <!-- property name="hibernate.connection.pool_size"></property -->

  <!-- dialect for MySQL -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hibernate.show_sql">True</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
     <mapping resource="User.hbm.xml"/>


    </session-factory>
</hibernate-configuration>

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.user">
 <class
  name="User"
  table="user"
 >
  <id
   name="Id"
   type="integer"
   column="id"
  >
   <generator class="native"/>
  </id>

  <property
   name="Name"
   column="name"
   type="string"
   not-null="true"
   length="20"
  />
  <property
   name="Password"
   column="password"
   type="string"
   not-null="true"
   length="20"
  />
  <component name="Contact" class="Contact">
   <property
   name="Email"
   column="email"
   type="string"
   not-null="false"
   length="50"
  />
  <property
   name="Address"
   column="address"
   type="string"
   not-null="false"
   length="100"
  />
  </component>
  


 </class> 
</hibernate-mapping>

 

3.测试
添加一个测试类:HibernateTest

package com.user;

import java.util.List;
import java.util.ListIterator;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateTest {
    public static void main(String[] args) throws HibernateException {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       
        //
        //testInsert(sessionFactory);
       
        //
        testQuery(sessionFactory);
       
         
        sessionFactory.close();
       
    }
    public static void testInsert( SessionFactory sessionFactory )throws HibernateException {
     
      Session session = sessionFactory.openSession();
        Transaction tx= session.beginTransaction();
        User user = new User();
        Contact contact=new Contact();
        contact.setEmail("email");
        contact.setAddress("address");
       
        user.setName("caterpillar");
        user.setPassword("password");
        user.setContact(contact);
       
        session.save(user);
        tx.commit();
        session.close();
        System.out.println("OK!");
   }
   
    public static void testQuery( SessionFactory sessionFactory )throws HibernateException {
     
     Session session = sessionFactory.openSession();
        Transaction tx= session.beginTransaction();
        User user = new User();
        Contact contact=new Contact();
                 
        Query query=session.createQuery("from User as user");
        //query.setCharacter(1, 'M');
        List names =query.list();
        for(ListIterator it=names.listIterator();it.hasNext();){
           user= (User)it.next();
           System.out.println("Id: " + user.getId());
            System.out.println("name: " + user.getName());
            System.out.println("password: " + user.getPassword());
            if(user.getContact()!=null){
             
             if(user.getContact().getEmail()!=null){
              System.out.println("Email: " + user.getContact().getEmail());
             }
             if(user.getContact().getAddress()!=null){
              System.out.println("Address: " + user.getContact().getAddress());
               
             }
            }
           
           
           
        }
         
      
        tx.commit();
        session.close();
     
    }
}

 

  

 

posted @ 2005-12-10 12:50 all gone 阅读(5013) | 评论 (3)编辑 收藏

Eclipse下JSF入门

1.开发环境
   与Eclipse下Struts的开发类似,安装好Eclipse和Tomcat之后,还需要两个插件:tomcat 插件和JSF插件(如果相关插件还没有安装),以下是相关下载地址:
    Eclipse SDK:
        http://www.eclipse.org/downloads/index.php 
    JSF:
     https://sourceforge.jp/projects/amateras/files/  
      FaceIDE+htmlEditor,htmlEditer也是必要的
    Tomcat :
         http://www.sysdeo.com/eclipse/tomcatplugin 
    Plugin Search:
         http://eclipse-plugins.2y.net/eclipse/search.jsp 
   插件的安装和配置有问题请直接Google。
2.开始
    入门嘛,我们就找一个最简单的Login就可以了

    新建Tomcat project
    加入JSF支持

    新建一个ManagedBean:


/**
 *
 */
package com.jsf;




/**
 * @author lzy
 *
 */
public class UserBean {
private String name;
    private String password;
public String verify() {
     if(this.name.equals("name")&&this.password.equals("password"))
     
        return "failure";

   else
        return "success";
}

 
/**
* @return Returns the name.
*/
public String getName() {
return name;
}

/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}


/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}

/**
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}


}

     新建两个JSP页面,login.jsp,welcom.jsp

login.jsp
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head>
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head>
<link href="main.css" rel="stylesheet"/>
<title></title>

</head>
<body>
    <f:view>
    <f:loadBundle basename="com.jsf.MessageResources" var="msgs"></f:loadBundle>
   
        <h:form>
        <h:panelGrid columns="3" headerClass="header" rowClasses="evenRow,oddRow">
        <f:facet name="header" >
        <h:outputText value="#{msgs.header}"/>
        </f:facet>
       
        <h:outputText value="#{msgs.namePromt}"></h:outputText>
        <h:inputText id="name"  required="true" value="#{user.name}">
        <f:validateLength minimum="2" maximum="10"></f:validateLength>
        </h:inputText>
        <h:message for="name" errorClass="errors"/>
       
       
        <h:outputText value="#{msgs.passwordPromt}"></h:outputText>
       
        <h:inputSecret id="password" value="#{user.password}" required="true" redisplay="true">
        <f:validateLength minimum="2"></f:validateLength>
        </h:inputSecret>
        <h:message for="password"/>
       
       
              <f:facet name="footer" >
        <h:outputText value="#{msgs.footer}"/>
        </f:facet>
        </h:panelGrid>          
            <h:commandButton value="#{msgs.submitPromt}" action="#{user.verify}"/>
            <h:commandButton value="#{msgs.resetPromt}" type="reset"/>
        </h:form>
    </f:view>
</body>
</html>



welcome.jsp


<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
</head>
<body>
    <f:view>
        <h:outputText value="#{user.name}"/>  is a good boy!
        <h3>welcome JavaServer Faces</h3>
    </f:view>
</body>

</html>
     编辑WEB-INF/lib下的faces-config.xml

struts-config.xml

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<navigation-rule>
        <from-view-id>/login.jsp</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/welcome.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>failure</from-outcome>
            <to-view-id>/login.jsp</to-view-id>
        </navigation-case>
</navigation-rule>


<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>com.jsf.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>


       最后是资源文件

# --login.jsp--
header=Welcom
namePromt=Name:
passwordPromt=Password:
amountPromt=Amount:
datePromt=Date:
submitPromt=Submit
resetPromt=Reset
footer=Thank you!


3.测试
在test工程中选择tomcat project->Update context definition
然后运行Tomcat
http://127.0.0.1:8080/jsfTest/login.jsf

posted @ 2005-12-10 12:05 all gone 阅读(17610) | 评论 (11)编辑 收藏

仅列出标题
共17页: First 上一页 6 7 8 9 10 11 12 13 14 下一页 Last