案例41-hibernate联系-添加客户

Posted jepson6669

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了案例41-hibernate联系-添加客户相关的知识,希望对你有一定的参考价值。

1 utils部分

1 HibernateUtils

package www.test.utils;

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

public class HibernateUtils {

    private static SessionFactory sf;
    static{
        // 1 创建,调用空参构造
        Configuration conf = new Configuration().configure();
        // 2 根据配置信息,创建 SessionFactory对象
        sf = conf.buildSessionFactory();
    }
    
    // 获得session==>获得全新的session
    public static Session openSession() {
        // 3 获得session
        Session session = sf.openSession();
        return session;
    }
    // 获得session==>获得与线程绑定的session
    public static Session getCurrentSession() {
        // 3 获得session
        Session session = sf.getCurrentSession();
        return session;
    }
    /*public static void main(String[] args) {
        System.out.println(HibernateUtils.openSession());
    }*/
}

2 BeanFactory

package www.test.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
@SuppressWarnings("all")
public class BeanFactory {

    public static Object getBean(String id){
        //生成对象--根据清单生产--配置文件--将每一个bean对象的生产细节配置到配置文件中
        
        //使用dom4j的xml解析技术 导入两个jar包
        // dom4j-1.6.1.jar 和 jaxen-1.1-beta-6.jar
        
        try {
            // 1 创建解析器
            SAXReader reader = new SAXReader();
            // 2 解析文档--bean.xml 在src下面
            String path = BeanFactory.class.getClassLoader().getResource("bean.xml").getPath();
              //读取
            Document doc = reader.read(path);
            
            
            // 3 获得元素--参数是xpath规则
            Element element = (Element) doc.selectSingleNode("//bean[@id=\'"+id+"\']");
            //<bean id="adminService" class="www.test.service.impl.AdminServiceImpl"></bean>
            String className = element.attributeValue("class"); 
            //www.test.service.impl.AdminServiceImpl
            
            //使用反射创建对象
            Class clazz = Class.forName(className);
            Object object = clazz.getDeclaredConstructor().newInstance();
            
            return object;
            
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        
        return null;
    }
}

2 domain部分

1 Customer实体类

package www.test.domain;

public class Customer {
    
    /*
     * CREATE TABLE `cst_customer` (
      `cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT \'客户编号(主键)\',
      `cust_name` VARCHAR(32) NOT NULL COMMENT \'客户名称(公司名称)\',
      `cust_source` VARCHAR(32) DEFAULT NULL COMMENT \'客户信息来源\',
      `cust_industry` VARCHAR(32) DEFAULT NULL COMMENT \'客户所属行业\',
      `cust_level` VARCHAR(32) DEFAULT NULL COMMENT \'客户级别\',
      `cust_linkman` VARCHAR(64) DEFAULT NULL COMMENT \'联系人\',
      `cust_phone` VARCHAR(64) DEFAULT NULL COMMENT \'固定电话\',
      `cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT \'移动电话\',
      PRIMARY KEY (`cust_id`)
    ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
     */
    private Long cust_id;
    
    private String cust_name;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_linkman;
    private String cust_phone;
    private String cust_mobile;
    public Long getCust_id() {
        return cust_id;
    }
    public void setCust_id(Long cust_id) {
        this.cust_id = cust_id;
    }
    public String getCust_name() {
        return cust_name;
    }
    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }
    public String getCust_source() {
        return cust_source;
    }
    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }
    public String getCust_industry() {
        return cust_industry;
    }
    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }
    public String getCust_level() {
        return cust_level;
    }
    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }
    public String getCust_linkman() {
        return cust_linkman;
    }
    public void setCust_linkman(String cust_linkman) {
        this.cust_linkman = cust_linkman;
    }
    public String getCust_phone() {
        return cust_phone;
    }
    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }
    public String getCust_mobile() {
        return cust_mobile;
    }
    public void setCust_mobile(String cust_mobile) {
        this.cust_mobile = cust_mobile;
    }
    @Override
    public String toString() {
        return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + "]";
    }
    
    
    

}
View Code

2 Customer.hbm.xml元数据配置文件(映射文件)

<?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">
<!-- 配置表与实体的关系 -->
<!-- package属性:填写一个包名。在元素内部凡是需要书写完整类名得属性,可以直接写简单类名就可以了 -->
<hibernate-mapping package="www.test.domain">
    <!--Class元素:配置实体与表得对应关系得
            name:完整类名
            table:数据库表名
      -->
    <class name="Customer" table="cst_customer">
    <!--id:配置主键映射得属性
            name:填写主键对应得属性名
            column:填写表中得主键得列名   默认值:列名会默认使用属性名
            type:填写列(属性)得类型。hibernate会自动检测实体的属性类型
                 每个类型有三种写法:分别是java类型 | hibernate类型 | 数据库类型
                java类型:             
                <property name="cust_name" column="cust_name" type="java.lang.String"></property>
                hibernate类型:
                <property name="cust_name" column="cust_name" type="string"></property>
                数据库类型:
                <property name="cust_name" column="cust_name" >
                    <column name="cust_name" sql-type="varchar"></column>
                </property>
            
                注意:不建议指定,自动检测实体属性类型就可以。
            
            not-null(可选):配置该属性(列)是否不能为空,默认值false默认可以为空
                <property name="cust_name" column="cust_name" not-null="true"></property>
            
            length(可选):配置数据库中列的长度。 默认值:使用数据库类型的最大长度 varchar默认最大长度255。
      -->
        <id name="cust_id" column="cust_id" >
        <!-- generator:主键生成得策略(后面讲) -->
            <generator class="native"></generator>
        </id>
        
        <!-- property:配置除了id之外得普通属性映射
                    name:填写属性名
                    column(可选):填写属性对应得列名 默认值:列名会默认使用属性名
                    type:填写列(属性)得类型。hibernate会自动检测实体的属性类型
                         每个类型有三种写法:分别是java类型 | hibernate类型 | 数据库类型
                        java类型:             
                        <property name="cust_name" column="cust_name" type="java.lang.String"></property>
                        hibernate类型:
                        <property name="cust_name" column="cust_name" type="string"></property>
                        数据库类型:
                        <property name="cust_name" column="cust_name" >
                            <column name="cust_name" sql-type="varchar"></column>
                        </property>
                    
                        注意:不建议指定,自动检测实体属性类型就可以。
                    
                    not-null(可选):配置该属性(列)是否不能为空,默认值false默认可以为空
                        <property name="cust_name" column="cust_name" not-null="true"></property>
                    
                    length(可选):配置数据库中列的长度。 默认值:使用数据库类型的最大长度 varchar默认最大长度255。
                         
         -->
        <property name="cust_name" column="cust_name"></property>
        <property name="cust_source" column="cust_source"></property>
        <property name="cust_industry" column="cust_industry"></property>
        <property name="cust_level" column="cust_level"></property>
        <property name="cust_linkman" column="cust_linkman"></property>
        <property name="cust_phone" column="cust_phone"></property>
        <property name="cust_mobile" column="cust_mobile"></property>
    </class>
</hibernate-mapping>
View Code

3 wen层

1 BaseServlet

package www.test.web.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("all")
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        resp.setContentType("text/html;charset=UTF-8");
        
        try {
            // 1 获得请求的method方法
            String methodName = req.getParameter("method");
            // 2获得当前被访问的对象的字节码对象
            Class clazz = this.getClass(); //ProductServlet.class --- UserServlet.class
            // 3 获取当前字节码对象中指定的方法
            Method method = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            // 4 执行相应的方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}
View Code

2 CustomerServlet

package www.test.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import www.test.domain.Customer;
import www.test.service.CustomerService;
import www.test.utils.BeanFactory;
@SuppressWarnings("all")
public class CustomerServlet extends BaseServlet {

    private CustomerService customerService =(CustomerService) BeanFactory.getBean("customerService");

    // 1 新增用户addCustomer
    public void addCustomer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题通过GenericEncodingFilter
        
        // 1 获得参数并封装到Customer对象
        Customer customer = new Customer();
        try {
            BeanUtils.populate(customer, request.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            
            e.printStackTrace();
        }
        
        //2 调用Service保存客户
        customerService.save(customer);
        
        // 3 重定向到客户列表
        response.sendRedirect(request.getContextPath()+"/ListCustomerServlet");
        
    }

}
View Code

3 GenericEncodingFilter 解决全局乱码

package www.test.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 通用编码解决方案
 * 
 */
public class GenericEncodingFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 转型为与协议相关对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 对request包装增强
        HttpServletRequest myrequest = new MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

}

// 自定义request对象
class MyRequest extends HttpServletRequestWrapper {

    private HttpServletRequest request;

    private boolean hasEncode;

    public MyRequest(HttpServletRequest request) {
        super(request);// super必须写
        this.request = request;
    }

    // 对需要增强方法 进行覆盖
    @Override
    public Map getParameterMap() {
        // 先获得请求方式
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
            // post请求
            try {
                // 处理post乱码
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (method.equalsIgnoreCase("get")) {
            // get请求
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!hasEncode) { // 确保get手动编码逻辑只运行一次
                for (String parameterName : parameterMap.keySet()) {
                    String[] values = parameterMap.get(parameterName);
                    if (values != null) {
                        for (int i = 0; i < values.length; i++) {
                            try {
                                // 处理get乱码
                                values[i] = new String(values[i].getBytes("ISO-8859-1"), "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                hasEncode = true;
            }
            return parameterMap;
        }

        return super.getParameterMap();
    }

    @Override
    public String getParameter(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        if (values == null) {
            return null;
        }
        return values[0]; // 取回参数的第一个值
    }

    @Override
    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        return values;
    }

}
View Code

4 Service层

1 CustomerService接口

package www.test.service;

import www.test.domain.Customer;

public interface CustomerService {

    //保存客户
    void save(Customer customer);

}
View Code

2 CustomerServiceImpl实现类

package www.test.service.impl;

import www.test.dao.CustomerDao;
import www.test.domain.Customer;
import www.test.service.CustomerService;
import www.test.utils.BeanFactory;

public class CustomerServiceImpl implements CustomerService {

    private CustomerDao customerDao = (CustomerDao) BeanFactory.getBean("customerDao");

    @Override
    public void save(Customer customer) {
        //调用Dao保存客户
        customerDao .save(customer);
    }

    
}
View Code

5 Dao层

1 CustomerDao接口

package www.test.dao;

import www.test.domain.Customer;

public interface CustomerDao {

    //保存客户
    void save(Customer customer);

}

2 CustomerDaoImpl实现类

package www.test.dao.impl;

import org.hibernate.Session;
import org.hibernate.Transaction;

import www.test.dao.CustomerDao;
import www.test.domain.Customer;
import www.test.utils.HibernateUtils;

public class CustomerDaoImpl implements CustomerDao {

    @Override
    //保存客户
    public void save(Customer customer) {
        // 1 获得session
        Session session = HibernateUtils.openSession();
        // 2 打开事务
        Transaction transaction = session.beginTransaction();
        // 3执行保存
        session.save(customer);
        // 4提交事务
        transaction.commit();
        // 5关闭资源
        session.close();
    }

}

6 src下其它配置文件

1 hibernate.cfg.xml主配置

<?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>
        <!-- 
        #hibernate.dialect org.hibernate.dialect.mysqlDialect
        #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
        #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
        #hibernate.connection.driver_class com.mysql.jdbc.Driver
        #hibernate.connection.url jdbc:mysql:///test
        #hibernate.connection.username gavin
        #hibernate.connection.password 
        -->
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库的url -->
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate</property> <!-- /// 表示连接本机 -->
        <!-- 数据库连接的用户名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">root</property>
        <!-- 数据库方言
            不同的数据库中,sql语法略有区别,指定方言可以让hibernate框架生成sql语句时。针对数据库方言生成。
            sql99标准:DDL 定义语言       库表的增删改查
                       DML 控制语言      事务权限
                       DCL 操作语言       针对增删改查
                        注意事项:MySQL在选择方言时候,请选择最短的方言。
                                 org.hibernate.dialect.MySQLDialect
                       
                        
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 
        #hibernate.show_sql true  //打印生成的sql
        #hibernate.format_sql true  //格式化sql  如果不格式都会在一行
         -->
         <!--将hibernate生成的sql语言打印到控制台  -->
        <property name="hibernate.show_sql">true</property>
         <!--将hibernate生成的sql语句格式化(语法缩进)  -->
        <property name="hibernate.format_sql">true</property>
        
        <!-- 
        ## auto schema export 自动导出表结构 。  自动建表

        #hibernate.hbm2ddl.auto create-drop  自动建表。每次框架运行结束都会将所有的表删除。(开发环境中测试使用)
        #hibernate.hbm2ddl.auto create 自动建表。每次框架的运行都会自动创建新的表。以前表将会被覆盖,表数据会丢失,(开发环境中测试使用)
        #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表。如果已经存在不会再生成。如果表有变动。自动更新表(不会删除任何数据)
        #hibernate.hbm2ddl.auto validate 校验。不自动生成表。每次启动会校验数据库中表是否正确。校验失败
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 引入orm元数据
            路径书写:填写src下的路径
         -->
        <mapping resource="www/test/domain/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
View Code

2 bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <!-- 配置CustomerServiceImpl的清单 -->
    <bean id="customerService" class="www.test.service.impl.CustomerServiceImpl"></bean>
    <!-- 配置CustomerDaoImpl的清单 -->
    <bean id="customerDao" class="www.test.dao.impl.CustomerDaoImpl"></bean>
</beans>
View Code

7 webcontent部分

1 jsp/add.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段

Android - 片段中的联系人选择器

如何在活动和片段之间传递对象

hibernate框架学习笔记8:一对多关系案例

检索数据未出现在 ListView 的片段中

通讯录管理系统联系案例