JavaWeb_(Hibernate框架)Hibernate论坛项目中一对多案例

 

 

  基于SSH论坛小型项目  传送门

 

  用户和发帖进行举例

  一对多关系:一个用户可以发表多个帖子

  一对一关系:一个帖子属于一个用户发布

 

  创建数据库用户user表

 

CREATE TABLE `hforum`.`user` (
  `id` VARCHAR(50) NOT NULL,
  `username` VARCHAR(45) NULL,
  `password` VARCHAR(45) NULL,
  `name` VARCHAR(45) NULL,
  `email` VARCHAR(45) NULL,
  `telephon` VARCHAR(45) NULL,
  PRIMARY KEY (`id`));
Gary.sql

 

  创建数据库帖子paste表

 

CREATE TABLE `hforum`.`paste` (
  `id` VARCHAR(50) NOT NULL,
  `title` VARCHAR(200) NULL,
  `content` VARCHAR(255) NULL,
  `offer` INT NULL,
  `ansnum` INT NULL,
  `glancover` INT NULL,
  `createtime` VARCHAR(45) NULL,
  `userid` VARCHAR(50) NULL,
  PRIMARY KEY (`id`));
paste.sql

 

  用户登陆用户登陆成功,用户将从login.jsp跳转到index.jsp用户登陆失败,将重定向到login.jsp

  数据库中添加一条假数据

  

 

  

 

 

package com.Gary.dao;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;

import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils;

public class UserDao {

    //原生SQL查询
    public User findUesr(User user) {

        Session session = HibernateUtils.getCurrentSession();
        String sql = "select * from user where username = ? and password = ?";
        NativeQuery query = session.createSQLQuery(sql);
        query.setParameter(1, user.getUsername());
        query.setParameter(2, user.getPassword());
        query.addEntity(User.class);
        
        User temp = (User) query.uniqueResult();
        
        
        
        return temp;

    }

}
UserDao.java

 

package com.Gary.domain;

public class Paste {

    private String id;
    private String title;
    private String content;
    private Integer offer;
    private Integer ansnum;
    private Integer glanceover;
    private String createtime;
    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getOffer() {
        return offer;
    }
    public void setOffer(Integer offer) {
        this.offer = offer;
    }
    public Integer getAnsnum() {
        return ansnum;
    }
    public void setAnsnum(Integer ansnum) {
        this.ansnum = ansnum;
    }
    public Integer getGlanceover() {
        return glanceover;
    }
    public void setGlanceover(Integer glanceover) {
        this.glanceover = glanceover;
    }
    public String getCreatetime() {
        return createtime;
    }
    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }
    
    
    
    
}
Paste.java

 

package com.Gary.domain;

public class User {

    private String id;;
    private String username;
    private String password;
    
    private String name;
    private String email;
    private String telephone;
    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    
    
    
}
User.java

 

<?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="com.Gary.domain">
    <class name="User" table="user">
        <id name = "id">
            <generator class="uuid"></generator>
        </id>
        
        
        <property name="username" column="username"></property>
        <property name="password" column="password"></property>
        <property name="name" column="name"></property>
        <property name="email" column="email"></property>
        <property name="telephone" column="telephone"></property>
        

        
        
    </class>

</hibernate-mapping>
User.hbm.xml

 

package com.Gary.service;

import org.hibernate.Transaction;

import com.Gary.dao.UserDao;
import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils;

public class UserService {

    public boolean findUesr(User user) {
        
        UserDao userDao = new UserDao();
        //开启事务(查询不需要数据库保护)
        Transaction transaction = HibernateUtils.getCurrentSession().beginTransaction();
        
        User temp = null;
        
        try
        {
            temp = userDao.findUesr(user);
        }
        catch(Exception e)
        {
            transaction.rollback();
        }
        
        //提交事务
        transaction.commit();
        
        
        return temp==null?false:true;
    }

}
UserService.java

 

package com.Gary.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

    private static SessionFactory sessionFactory = null;
    
    static {
        Configuration config = new Configuration().configure();
        sessionFactory = config.buildSessionFactory();
    }
    
    public static Session getSession()
    {
        return sessionFactory.openSession();
    }
    
    public static Session getCurrentSession()
    {
        return sessionFactory.getCurrentSession();
    }
    
}
HibernateUtils.java

 

package com.Gary.web;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User>{

    public User user = new User();
    
    public String login() throws Exception {
        
        UserService userService = new UserService();
        
        boolean success = userService.findUesr(user);
        
        System.err.println(success);
        System.err.println(user.getUsername());
        System.err.println(user.getPassword());
        
        
        if(success)
        {
            return "toIndex";
        }
        else
        {
            ActionContext.getContext().put("error", "用户名或密码错误!!");
            return "login";
        }
        
        
    }

    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }

    
    
}
UserAction.java

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    

<hibernate-configuration>

    <session-factory>
    
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        
        <property name="hibernate.connection.url">jdbc:mysql:///hforum</property>
        
        <property name="hibernate.connection.username">root</property>
        
        <property name="hibernate.connection.password">123456</property>
        
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql"></property>
        
        <!-- 格式化hibernate生成的sql语句 -->
        <property name="hibernate.format_sql"></property>
        
        <!-- 配置hibernate自动创建表-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 配置数据库的隔离级别-->
        <property name="hibernate.connection.isolation">4</property>
        
        <!-- 配置事务 (session与当前线程绑定)  -->
        <property name="hibernate.current_session_context_class">thread</property>
    
        <mapping resource="com/Gary/domain/User.hbm.xml"/>
    
    </session-factory>

</hibernate-configuration>
hibernate.cfg.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>

    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    
    <package name="hibernateTest" namespace="/" extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
            
            <result name="toIndex" type="redirect">/index.jsp</result>
            <result name = "login">/login.jsp</result>
        </action>
    
    </package>
    

</struts>
struts.xml

 

  用户发布帖子

  一个用户可以发多个帖子,一个帖子对应一个用户

   数据库中的用户

  

 

  当用户登陆成功后,跳转至index.jsp首页面,用户可以进行发帖

  

 

  

 

 

package com.Gary.dao;

import org.hibernate.Session;

import com.Gary.domain.Paste;
import com.Gary.utils.HibernateUtils;

public class PasteDao {

    public void addPaste(Paste paste) {
        
        Session session = HibernateUtils.getCurrentSession();
        session.save(paste);
        
    }

}
PasteDao.java

 

package com.Gary.dao;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;

import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils;

public class UserDao {

    //原生SQL查询
    public User findUesr(User user) {

        Session session = HibernateUtils.getCurrentSession();
        String sql = "select * from user where username = ? and password = ?";
        NativeQuery query = session.createSQLQuery(sql);
        query.setParameter(1, user.getUsername());
        query.setParameter(2, user.getPassword());
        query.addEntity(User.class);
        
        User temp = (User) query.uniqueResult();
        
        
        
        return temp;

    }

}
UserDao.java

 

package com.Gary.domain;

public class Paste {

    private String id;
    private String title;
    private String content;
    private Integer offer;
    private Integer ansnum;
    private Integer glanceover;
    private String createtime;
    
    //一个帖子属于一个用户
    private User user;
    
    
    
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getOffer() {
        return offer;
    }
    public void setOffer(Integer offer) {
        this.offer = offer;
    }
    public Integer getAnsnum() {
        return ansnum;
    }
    public void setAnsnum(Integer ansnum) {
        this.ansnum = ansnum;
    }
    public Integer getGlanceover() {
        return glanceover;
    }
    public void setGlanceover(Integer glanceover) {
        this.glanceover = glanceover;
    }
    public String getCreatetime() {
        return createtime;
    }
    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }
    
    
    
    
}
Paste.java

 

package com.Gary.domain;

import java.util.HashSet;
import java.util.Set;

public class User {

    private String id;;
    private String username;
    private String password;
    
    private String name;
    private String email;
    private String telephone;
    
    //一对多
    private Set<Paste> pasteSet = new HashSet<Paste>();
    
    public Set<Paste> getPasteSet() {
        return pasteSet;
    }
    public void setPasteSet(Set<Paste> pasteSet) {
        this.pasteSet = pasteSet;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    
    
    
}
User.java

 

<?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="com.Gary.domain">
    <class name = "Paste" table="paste">
        <id name="id">
            <generator class="uuid"></generator>
        </id>
        
        <property name="title" column="title"></property>
        <property name="content" column="content"></property>
        <property name="offer" column="offer"></property>
        <property name="ansnum" column="ansnum"></property>
        <property name="glanceover" column="glanceover"></property>
        <property name="createtime" column="createtime"></property>
    
        <!-- name:引用属性名
                class:与他关系的对象的完整类名
                column:外键列名
         -->
         <!-- inverse:配置关系是否不维护
                         true:    不维护
                         false:    维护关系
                insert属性:
                性能优化:
                无论怎么放弃维护,总有一方需要维护(按照默认值来就行)
                一般的开发中,一的一方放弃维护,多的一方不放弃维护
        -->
        
        <!-- 
            <many-to-one name="user" class="User" column="userid" cascade="save-update,persist"></many-to-one>
         -->
    
            <many-to-one name="user" class="User" column="userid" ></many-to-one>
    
    </class>

</hibernate-mapping>
Paste.xml.hbm

 

<?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="com.Gary.domain">
    <class name="User" table="user">
        <id name = "id">
            <generator class="uuid"></generator>
        </id>
        
        
        <property name="username" column="username"></property>
        <property name="password" column="password"></property>
        <property name="name" column="name"></property>
        <property name="email" column="email"></property>
        <property name="telephone" column="telephone"></property>
        
            <!-- name:集合属性名字
                column:外键列名
                class:与他相关的对象的完整类名 -->
                <!-- 
                    cascade:级联操作
                        save-update:级联保存,级联更新
                        delete:级联删除
                        all
                 -->
                 <!-- inverse:配置关系是否不维护
                         true:    不维护
                         false:    维护关系
                  -->
            <set name="pasteSet">
                <key column="userid"></key>
                <one-to-many class="Paste"/>
            </set>
        
        
        
        
    </class>

</hibernate-mapping>
User.hbm.xml

 

package com.Gary.service;

import org.hibernate.Transaction;

import com.Gary.dao.PasteDao;
import com.Gary.domain.Paste;
import com.Gary.utils.HibernateUtils;

public class PasteService {

    public void addPaste(Paste paste) {
        
        PasteDao pasteDao = new PasteDao();
        
        Transaction beginTransaction = HibernateUtils.getCurrentSession().beginTransaction();
        
        try
        {
            pasteDao.addPaste(paste);
        }
        catch(Exception e)
        {
            beginTransaction.rollback();
        }
        
        beginTransaction.commit();
    }

}
PasteService.java

 

package com.Gary.service;

import org.hibernate.Transaction;

import com.Gary.dao.UserDao;
import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils;

public class UserService {

    public User findUesr(User user) {
        
        UserDao userDao = new UserDao();
        //开启事务(查询不需要数据库保护)
        Transaction transaction = HibernateUtils.getCurrentSession().beginTransaction();
        
        User temp = null;
        
        try
        {
            temp = userDao.findUesr(user);
        }
        catch(Exception e)
        {
            transaction.rollback();
        }
        
        //提交事务
        transaction.commit();
        
        
        return temp;
    }

}
UserService.java

 

package com.Gary.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

    private static SessionFactory sessionFactory = null;
    
    static {
        Configuration config = new Configuration().configure();
        sessionFactory = config.buildSessionFactory();
    }
    
    public static Session getSession()
    {
        return sessionFactory.openSession();
    }
    
    public static Session getCurrentSession()
    {
        return sessionFactory.getCurrentSession();
    }
    
}
HibernateUtils.java

 

package com.Gary.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.Gary.domain.Paste;
import com.Gary.domain.User;
import com.Gary.service.PasteService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class PasteAction extends ActionSupport implements ModelDriven<Paste>{

    public Paste paste = new Paste();
    
    //addPaste
    public String addPaste() throws Exception {
        
        //没有的数据手动封装
        //title  content  offer
        paste.setAnsnum(0);
        paste.setGlanceover(0);
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String createtime = format.format(date);
        paste.setCreatetime(createtime);
        User user = (User) ActionContext.getContext().getSession().get("user");
        paste.setUser(user);
        
        PasteService pasteService = new PasteService();
        pasteService.addPaste(paste);
        
        return "toIndex";
    }

    @Override
    public Paste getModel() {
        
        return paste;
    }

    
    
}
PasteAction.java

 

package com.Gary.web;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User>{

    public User user = new User();
    
    public String login() throws Exception {
        
        UserService userService = new UserService();
        
        User temp = userService.findUesr(user);
        
        if(temp!=null)
        {
            ActionContext.getContext().getSession().put("user", temp);
            return "toIndex";
        }
        else
        {
            ActionContext.getContext().put("error", "用户名或密码错误!!");
            return "login";
        }
        
        
    }

    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }

    
    
}
UserAction.java

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    

<hibernate-configuration>

    <session-factory>
    
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        
        <property name="hibernate.connection.url">jdbc:mysql:///hforum</property>
        
        <property name="hibernate.connection.username">root</property>
        
        <property name="hibernate.connection.password">123456</property>
        
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql"></property>
        
        <!-- 格式化hibernate生成的sql语句 -->
        <property name="hibernate.format_sql"></property>
        
        <!-- 配置hibernate自动创建表-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 配置数据库的隔离级别-->
        <property name="hibernate.connection.isolation">4</property>
        
        <!-- 配置事务 (session与当前线程绑定)  -->
        <property name="hibernate.current_session_context_class">thread</property>
    
        <mapping resource="com/Gary/domain/User.hbm.xml"/>
        <mapping resource="com/Gary/domain/Paste.hbm.xml"/>
    
    
    </session-factory>

</hibernate-configuration>
hibernate.cfg.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>

    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    
    <package name="hibernateTest" namespace="/" extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
            
            <result name="toIndex" type="redirect">/index.jsp</result>
            <result name = "login">/login.jsp</result>
        </action>
    
        <action name="PasteAction_*" class="com.Gary.web.PasteAction" method="{1}">
            <result name="toIndex" type="redirect">/index.jsp</result>
        </action>
    
    </package>
    

</struts>
struts.xml

 

   级联操作:级联(cascade)在计算机科学里指多个对象之间的映射关系,建立数据之间的级联关系提高管理效率

hibernate-mapping package="com.Gary.domain">
    <class name="User" table="user">
        <id name = "id">
            <generator class="uuid"></generator>
        </id>
        
        
        <property name="username" column="username"></property>
        <property name="password" column="password"></property>
        <property name="name" column="name"></property>
        <property name="email" column="email"></property>
        <property name="telephone" column="telephone"></property>
        
            <!-- name:集合属性名字
                column:外键列名
                class:与他相关的对象的完整类名 -->
                <!-- 
                    cascade:级联操作
                        save-update:级联保存,级联更新
                        delete:级联删除
                        all
                 -->
                 <!-- inverse:配置关系是否不维护
                         true:    不维护
                         false:    维护关系
                  -->
                  
                  
            <set name="pasteSet">
                <key column="userid"></key>
                <one-to-many class="Paste"/>
            </set>
        
    </class>

</hibernate-mapping>

 

   inverse操作

<hibernate-mapping package="com.Gary.domain">
    <class name = "Paste" table="paste">
        <id name="id">
            <generator class="uuid"></generator>
        </id>
        
        <property name="title" column="title"></property>
        <property name="content" column="content"></property>
        <property name="offer" column="offer"></property>
        <property name="ansnum" column="ansnum"></property>
        <property name="glanceover" column="glanceover"></property>
        <property name="createtime" column="createtime"></property>
    
        <!-- name:引用属性名
                class:与他关系的对象的完整类名
                column:外键列名
         -->
         <!-- inverse:配置关系是否不维护
                         true:    不维护
                         false:    维护关系
                insert属性:
                性能优化:
                无论怎么放弃维护,总有一方需要维护(按照默认值来就行)
                一般的开发中,一的一方放弃维护,多的一方不放弃维护
        -->
        
    
            <many-to-one name="user" class="User" column="userid" ></many-to-one>
    
    </class>

</hibernate-mapping>

 

 

 

 

 

 

 

 

 

posted @ 2019-11-24 15:16  Cynical丶Gary  阅读(291)  评论(0编辑  收藏  举报