为什么我一直强调使用new和delete时要采取相同的形式

本文详细解析了C++中对象数组的内存分配和释放,强调了new[]和delete[]的匹配使用。通过实例展示了不正确释放对象数组导致的内存泄漏和运行时错误,并解释了内存模型中‘数组大小’记录的重要性。最后,提出了正确的对象数组内存管理策略,防止内存泄漏和程序崩溃。

有如下类:

class point_ty{
private:
	int x;
	int y;
	int z;
public:
	point_ty(int a, int b,int c) :x(a), y(b),z(c)
	{
		
	}
	point_ty() :x(0), y(0),z(0)
	{
		
	}
	void show()
	{
		cout << this << " x:" << x << " y:" << y << endl;
	}

	~point_ty()
	{
		cout <<"~point_ty"<< endl;
	}
};

如下使用:

void main()
{
	point_ty *ptr = new point_ty(1, 2,3);
	ptr->show();
	delete ptr;
	ptr = NULL;
	system("pause");
}

其实编译器将point_ty *ptr = new point_ty(1, 2);转化为如下语句:
1)void *pTmp = ::operator new[sizeof(point_ty)];
2) ptr = static_cast<point_ty *>(pTmp);
3) ptr->point_ty::point_ty(1,2);//注意只有编译器才可以这样调用构造函数

貌似这种单个指针的使用,只要细心大家都不太会出问题,接下来讲解一下另一种情况(对象数组)

如下使用

void main()
{
	int *pa = new int[10];
	delete pa;
	system("pause");
}

我相信,工作中有很多人这样写代码,的确对于普通类型来说没有问题,因为它的内存布局类似如下:
在这里插入图片描述
这样是不会造成内存泄漏的,但如果是类对象呢?如下使用方法:

void main()
{
	point_ty *ptr = new point_ty[3];
	delete ptr;
	ptr = NULL;
	system("pause");
}

结果:
在这里插入图片描述
这个结果对于初学者来说是很出乎意料的。到底是什么原因造成这种结果的呢?其实只需要知道申请内存是对象数组的内存模型就可以知道原因,下面我画图示意一下。
在这里插入图片描述
单一对象的内存布局不同于数组的内存布局,明确点说:数组所用的内存通常还包括“数组的大小”的记录,这个记录用于执行几次析构函数,上述使用过程造成的奔溃就是因为漏掉了“3”所占用的那部分空间,造成布局不同了。那该如何解决奔溃的问题呢?其实很简单,就是使用 delete []ptr.因为这样使用,在释放内存的时候,会自动将ptr的指针指向带有记录数量的地址处,从而可以正确释放内存。接下来给出正确释放对象数组的内存布局示意图。

在这里插入图片描述
总结
如果你在new表达式中使用[],必须在相应的delete表达式中也使用[],如果你在new表达式中不使用[],一定不要在相应的delete表达式中使用[].

有兴趣的同学可以测试,使用new,然后再使用 delete []。结果如果使用对象,且定义了析构函数当然奔溃。

根据以下帮我写完整的前后端代码 ,还有步骤内容要具体完整 第一部分 电子商务系统设计概述 应用《高级语言程序设计Ⅱ(Java)》、《电子商务网站设计与开发》、《J2EE电子商务系统开发技术》、《数据处理与数据库A》、《管理信息系统》等课程内容设计与开发电子商务系统。“电子商务系统设计”强调从总体结构、系统分析、系统开发这一角度来研究电子商务系统。任何一个电子商务系统都离不开后台数据库的支持,所以本实践将Java技术、Java EE技术以及数据库技术有效的结合起来,开发一个以数据库技术为支持的WEB应用系统。电子商务系统设计的目的要求如下: 一、课程设计目的意义   1. 加深对讲授内容的理解 《J2EE电子商务系统开发技术》理论课强调实用性,注重学生动手能力的培养。本课程设计将有助于加深对《管理信息系统》、《J2EE电子商务系统开发技术》、《数据处理与数据库A》等课程内容的基本概念、基本原理、设计原则数据库操纵方法的理解。   2. 通过电子商务系统设计与开发,掌握电子商务系统设计与开发的关键技术,培养自主开发能力。 电子商务系统设计侧重于理论应用、系统设计程序开发过程。结合实际需要开发一个特定的“电子商务后台管理系统”,使学生能够运用Java EE技术,结合数据库的基本知识设计数据库,掌握技术方法,掌握面向对象程序设计分析的基本思想基本方法,掌握Java EE开发的三层结构、能够自主设计并实现小型的软件,最终具备一定的自主开发能力。使同学能够主动查阅与Java EE应用程序开发的相关资料,具备文献检索能力。进而能够与国内外IT行业对人才的需求接轨,为后面的毕业设计将来能够较好地适应社会需求打下基础。 3. 培养自学以及主动解决问题的能力 通过本次设计,使同学能够主动查阅与应用网站相关资料,掌握一些课堂上老师未曾教授的知识,从而达到培养学生自学以及主动解决问题的能力的目的,为后面的毕业设计打下坚实的基础。 二、课程设计实施步骤 同学们可按下列步骤完成题目的设计并写出设计报告。 第一步:问题分析。 查找网上现有的电子商务网站,对网站进行分析,掌握网站主要功能。在对电子商务网站进行调研的基础上,明确本系统完成内容。依据调查结果,进一步分析表达用户的需求,绘制实体关系图。 第二步:数据库设计与实现。包括: 数据库的概念结构(E-R)图: 逻辑与物理结构设计:将E-R图转换为关系模型,及设计数据库中的表、视图(如果使用)、存储过程(如果使用)的结构定义(可以用SQL脚本提供); 设计系统查询功能及要求,写出主要的查询SQL语句。 第三步:系统功能设计与实现,确定系统开发所使用技术方案,确定系统开发的功能结构,描述每一个所完成功能的类之间交互的序图。 第四步:完成系统开发。使用Spring MVC框架、JPA技术以及mysql数据库,开发系统功能。使用Java EE三层结构进行系统开发,即首先开发DAO层,完成对数据库的CRUD,然后进行业务逻辑层的开发,最后使用HTML等前端技术完成页面开发,并对其中的关键部分编写测试程序。 第五步:实践报告编写:按照报告书格式要求,编写实践报告。 三、课程设计要求 本次课程设计的目标是运用Java EE技术数据库技术以及管理信息系统知识完成一个电子商务后台管理系统的的设计与开发工作。为了巩固学生掌握的Java EE技术,课程设计采用Spring MVC框架、JPA等技术进行系统开发。数据库不做强制要求,推荐使用mysql。课程设计结束后,学生以文档的形式提交课程设计成果,软件要实际上机检查,要求具有一定的实用性。 设计报告具体要求如下: (1)系统分析:数据库设计(E-R图)、功能模块图、系统软件技术方案。 (2)系统实施计划:列出系统实施的间进度安排。 (3)登录界面:登录界面截图,界面程序及系统登录业务逻辑的核心程序。 (4)系统首页:系统首页截图,系统首页核心程序。 (5)用户管理功能:实现用户列表的展示、用户信息添加、用户修改、删除及查询、展示系统截图、绘制类之间相互调用的序图及核心程序。 (6)商品管理功能:实现商品列表的展示、商品添加、商品修改以及删除查询,展示系统截图、绘制类之间相互调用的序图及核心程序。 第二部分 课程设计指导 一、项目开发的一般流程 1.需求确定 通过各种手段(头脑风暴、会议、询问、原型——界面原型业务原型)确定系统的功能性能。 2.分析与设计 1)架构分析与设计 2)业务逻辑分析 3)业务逻辑设计 4)界面设计 3.开发环境搭建 4.开发-测试-开发-测试(螺旋递增式开发) 5.文档编写 二、需求分析 1.问题的提出: 传统的网站管理方式有两种:一是静态HTML页面,更新信息需要重新制作页面,然后上传页面并修改相应的链接,这种方式因为效率太低已不多用;二是基于J2EE脚本语言,将动态网页数据库结合,通过应用程序来处理程序,这是目前较为流行的做法。网络广告系统充分发挥网络的优势,实现了网络广告的动态管理,使得对网络广告的管理更加方便、及、安全,降低了升级维护的难度,提高了工作效率。 2.系统需要解决的问题及功能: 根据实现业务的不同进行功能分析。 三、系统分析与设计 1.架构分析与设计 逻辑架构:3层架构、n层架构;MVC等; 物理架构:Web服务器的分布;数据库服务器的分布; 技术解决方案的确定: PHP;Open Source; 2.业务逻辑分析 (Unified Process,Use Case) -根据需求分析业务逻辑 -他们会使用本系统做什么 -通常他们使用本系统的步骤是什么样的 -会有哪些明显的类来支撑本系统的运行 -会有哪些不同的提示返回给用户 本阶段与需求的确定密切相关,通常在确定需求的候会进行相关的分析 3.业务逻辑设计 -根据需求的分析来确定具体的类 -确定类的属性 -确定类的接口(方法) -确定类之间的关系 -确定用户操作流程在设计上的反映 -进行数据库的设计(不同的项目步骤可能不尽相同) 4.界面设计 -设计系统的界面风格: 颜色,style -设计系统的具体“模拟”界面 能够从头走到尾:方便进行需求的确定;方便程序员的开发 (界面设计:注意命名机制,包括文件名、字段名等;风格要统一,最好画图表示出来,不用文字) 四、开发环境搭建 -开发工具的确定 -配置管理工具的确定 -测试工具的确定 -文件服务器/配置服务器的确定 五、开发-测试-开发-测试 -按照设计进行开发 -迅速开发原型 -进行迭代开发 -提早进行测试 -单元测试 -黑盒测试 -性能测试 -应用性测试 第三部分 设计描述 本部分讲述如何用Java EE技术开发一个简易的电子商务后台系统,其目的是掌握一般的信息系统开发的常用方法,以及使学生熟练掌握基于Java EE开发系统的过程及技术的使用。系统采用Spring MVC框架、JPA技术等;本系统采用的是MySql数据库。 一、系统模块构成 本次实践所完成的主要功能模块主要包括一下部分: (1)用户管理模块 包括用户会员的添加、删除以及修改查询。 (2)商品管理模块 包括商品的添加、删除以及修改查询。 (3)库存查询 主要查询每一件商品的当前库存数量。 (4)权限管理 实现用户的功能权限的过滤管理。 系统模块如下图所示: 二、数据库设计 在这个阶段,根据所了解掌握的用户需求,进行了数据的采集对数据的处理操作,以确保数据采集的详细准确,理清数据库中各个数据项的关系,这将为系统的设计打基础。在数据分析阶段要做到两点: 调查清楚应用系统用户所需要操作的数据,决定存储什么数据。 调查清楚应用系统用户要求对数据进行什么样的处理,理清各个数据项之间的关系。 注意做到这两点是十分重要的要向系统用户详细调查保证信息的采集的完整性、一致性准确性。在数据分析后要做到设计出一个数据字典文档包括三方面: (1) 数据项:包括字段名、字段的含义、类型定义以及其他数据项的逻辑关系。 (2) 数据结构:若干个数据项的有意义的集合,包括字段名称、含义以及组成的数据结构的数据项。 (3) 数据流:指数据库中数据的处理过程,包括数据信息的输入、处理输出。 据此,可归结出内容管理系统所需完成的主体任务: (1) 基本信息的添加、修改删除:包括用户商品等信息。 (2) 基本信息的查询:商品信息的查询。 针对内容管理系统的总体需求,通过对系统的内容数据流程分析与系统总体功能模块梳理,主要的实体关系图如下图所示: 三、技术方案 本系统是基于Java EE技术,采用B/S结构,B/S体系结构的客户端是Web浏览器,它负责实现显示交互。应用服务器是位于Web服务器端,它的任务是接受用户的请求,执行相应的应用程序并与数据库进行连接,通过SQL等方式向数据库服务器提出数据处理申请,并将数据处理的结果提交给Web服务器,再由Web服务器传送回客户端。数据库服务器负责接受Web服务器对数据操作的请求,实现对数据库查询、修改、更新等功能,把运行结果提交给Web服务器。如下图所示,是基于B/S的三层体系结构。 第四部分 实验内容 一、用户管理(核心实现部分) 1.1 实体类: package cn.edu.xiyou; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * Teacheruser entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "teacheruser", catalog = "teacher") public class Teacheruser implements java.io.Serializable { // Fields private Integer id; private String name; private Integer age; private String password; // Constructors /** default constructor */ public Teacheruser() { } /** full constructor */ public Teacheruser(String name, Integer age) { this.name = name; this.age = age; } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "name", length = 32) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "age") public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } @Column(name = "password", length = 32) public String getPassWord() { return this.password; } public void setPassWord(String name) { this.password = name; } } 1.2 DAO接口层(CRUD) package cn.edu.xiyou; import java.util.List; /** * Interface for TeacheruserDAO. * * @author MyEclipse Persistence Tools */ public interface ITeacheruserDAO { /** * Perform an initial save of a previously unsaved Teacheruser entity. All * subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * ITeacheruserDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Teacheruser entity to persist * @throws RuntimeException * when the operation fails */ public void save(Teacheruser entity); /** * Delete a persistent Teacheruser entity. This operation must be performed * within the a database transaction context for the entity's data to be * permanently deleted from the persistence store, i.e., database. This * method uses the {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * ITeacheruserDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Teacheruser entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Teacheruser entity); /** * Persist a previously saved Teacheruser entity and return it or a copy of * it to the sender. A copy of the Teacheruser entity parameter is returned * when the JPA persistence mechanism has not previously been tracking the * updated entity. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = ITeacheruserDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Teacheruser entity to update * @return Teacheruser the persisted Teacheruser entity instance, may not be * the same * @throws RuntimeException * if the operation fails */ public Teacheruser update(Teacheruser entity); public Teacheruser findById(Integer id); /** * Find all Teacheruser entities with a specific property value. * * @param propertyName * the name of the Teacheruser property to query * @param value * the property value to match * @return List<Teacheruser> found by query */ public List<Teacheruser> findByProperty(String propertyName, Object value); public List<Teacheruser> findByName(Object name); public List<Teacheruser> findByAge(Object age); /** * Find all Teacheruser entities. * * @return List<Teacheruser> all Teacheruser entities */ public List<Teacheruser> findAll(); } 1.3 DAO层(实现Dao接口中的方法) package cn.edu.xiyou; import java.util.List; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.Query; /** * A data access object (DAO) providing persistence and search support for * Teacheruser entities. Transaction control of the save(), update() and * delete() operations must be handled externally by senders of these methods or * must be manually added to each of these methods for data to be persisted to * the JPA datastore. * * @see cn.edu.xiyou.Teacheruser * @author MyEclipse Persistence Tools */ public class TeacheruserDAO implements ITeacheruserDAO { // property constants public static final String NAME = "name"; public static final String AGE = "age"; private EntityManager getEntityManager() { return EntityManagerHelper.getEntityManager(); } /** * Perform an initial save of a previously unsaved Teacheruser entity. All * subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * TeacheruserDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Teacheruser entity to persist * @throws RuntimeException * when the operation fails */ public void save(Teacheruser entity) { EntityManagerHelper .log("saving Teacheruser instance", Level.INFO, null); try { EntityManager em = getEntityManager(); em.getTransaction().begin(); em.persist(entity); em.flush(); em.getTransaction().commit(); EntityManagerHelper.log("save successful", Level.INFO, null); } catch (RuntimeException re) { EntityManagerHelper.log("save failed", Level.SEVERE, re); throw re; } } /** * Delete a persistent Teacheruser entity. This operation must be performed * within the a database transaction context for the entity's data to be * permanently deleted from the persistence store, i.e., database. This * method uses the {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * TeacheruserDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Teacheruser entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Teacheruser entity) { EntityManagerHelper.log("deleting Teacheruser instance", Level.INFO, null); try { entity = getEntityManager().getReference(Teacheruser.class, entity.getId()); getEntityManager().remove(entity); EntityManagerHelper.log("delete successful", Level.INFO, null); } catch (RuntimeException re) { EntityManagerHelper.log("delete failed", Level.SEVERE, re); throw re; } } /** * Persist a previously saved Teacheruser entity and return it or a copy of * it to the sender. A copy of the Teacheruser entity parameter is returned * when the JPA persistence mechanism has not previously been tracking the * updated entity. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = TeacheruserDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Teacheruser entity to update * @return Teacheruser the persisted Teacheruser entity instance, may not be * the same * @throws RuntimeException * if the operation fails */ public Teacheruser update(Teacheruser entity) { EntityManagerHelper.log("updating Teacheruser instance", Level.INFO, null); try { EntityManager em = getEntityManager(); em.getTransaction().begin(); Teacheruser result = em.merge(entity); em.getTransaction().commit(); EntityManagerHelper.log("update successful", Level.INFO, null); return result; } catch (RuntimeException re) { EntityManagerHelper.log("update failed", Level.SEVERE, re); throw re; } } public Teacheruser findById(Integer id) { EntityManagerHelper.log("finding Teacheruser instance with id: " + id, Level.INFO, null); try { Teacheruser instance = getEntityManager().find(Teacheruser.class, id); return instance; } catch (RuntimeException re) { EntityManagerHelper.log("find failed", Level.SEVERE, re); throw re; } } /** * Find all Teacheruser entities with a specific property value. * * @param propertyName * the name of the Teacheruser property to query * @param value * the property value to match * @return List<Teacheruser> found by query */ @SuppressWarnings("unchecked") public List<Teacheruser> findByProperty(String propertyName, final Object value) { EntityManagerHelper.log("finding Teacheruser instance with property: " + propertyName + ", value: " + value, Level.INFO, null); try { final String queryString = "select model from Teacheruser model where model." + propertyName + "= :propertyValue"; Query query = getEntityManager().createQuery(queryString); query.setParameter("propertyValue", value); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find by property name failed", Level.SEVERE, re); throw re; } } public List<Teacheruser> findByName(Object name) { return findByProperty(NAME, name); } public List<Teacheruser> findByAge(Object age) { return findByProperty(AGE, age); } /** * Find all Teacheruser entities. * * @return List<Teacheruser> all Teacheruser entities */ @SuppressWarnings("unchecked") public List<Teacheruser> findAll() { EntityManagerHelper.log("finding all Teacheruser instances", Level.INFO, null); try { final String queryString = "select model from Teacheruser model"; Query query = getEntityManager().createQuery(queryString); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find all failed", Level.SEVERE, re); throw re; } } } 1.4 Controller package cn.edu.xiyou.controller; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import cn.edu.xiyou.Teacheruser; import cn.edu.xiyou.TeacheruserDAO; @Controller public class TestController { TeacheruserDAO td = new TeacheruserDAO(); @RequestMapping("/test.do") public String test(String username,String password,Model model){ System.out.println("the username is ==="+username); System.out.println("the password is ==="+password); List<Teacheruser> tus = td.findByName(username); Teacheruser tu = tus.get(0); if(tu.getPassWord().equals(password)){ System.out.println("login success"); model.addAttribute("result","success"); }else{ System.out.println("login filure"); model.addAttribute("result","failure"); } return "hello"; } @RequestMapping("/test2.do") public String test2(String username2,String password2,String age,Model model){ System.out.println("the username is ==="+username2); System.out.println("the password is ==="+password2); Teacheruser tu = new Teacheruser(); tu.setAge(Integer.parseInt(age)); tu.setName(username2); tu.setPassWord(password2); td.save(tu); model.addAttribute("result",“成功”); return "hello2"; } @RequestMapping("/login.do") public String login(){ return "userlogin"; } @RequestMapping("/userverify.do") public String userLogin(String username,String password){ System.out.println("the username is ==="+username); System.out.println("the password is ==="+password); return ""; } } 二、Spring MVC配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="cn.edu.xiyou" /> <mvc:annotation-driven/> <!-- View Resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/> </beans> 三、JPA配置文件 <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="testJPA"> <class>cn.edu.xiyou.Teacheruser</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.cache.use_second_level_cache" value="false" /> <property name="hibernate.cache.use_query_cache" value="false" /> <property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/teacher"/> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.connection.username" value="root"/> <property name="hibernate.connection.password" value="123321"/> </properties> </persistence-unit> </persistence> 四、JPA基础类 package cn.edu.xiyou; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; /** * @author MyEclipse Persistence Tools */ public class EntityManagerHelper { private static final EntityManagerFactory emf; private static final ThreadLocal<EntityManager> threadLocal; private static final Logger logger; static { emf = Persistence.createEntityManagerFactory("testJPA"); threadLocal = new ThreadLocal<EntityManager>(); logger = Logger.getLogger("testJPA"); logger.setLevel(Level.ALL); } public static EntityManager getEntityManager() { EntityManager manager = threadLocal.get(); if (manager == null || !manager.isOpen()) { manager = emf.createEntityManager(); threadLocal.set(manager); } return manager; } public static void closeEntityManager() { EntityManager em = threadLocal.get(); threadLocal.set(null); if (em != null) em.close(); } public static void beginTransaction() { getEntityManager().getTransaction().begin(); } public static void commit() { getEntityManager().getTransaction().commit(); } public static void rollback() { getEntityManager().getTransaction().rollback(); } public static Query createQuery(String query) { return getEntityManager().createQuery(query); } public static void log(String info, Level level, Throwable ex) { logger.log(level, info, ex); } } 五、用户管理 5.1 实体类: package cn.edu.xupt.accounts; 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 cn.edu.xupt.users.Users; /** * Accounts entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "accounts", catalog = "wsy") public class Accounts implements java.io.Serializable { // Fields private Integer account; private Users users; private Double balance; // Constructors /** default constructor */ public Accounts() { } /** minimal constructor */ public Accounts(Integer account) { this.account = account; } /** full constructor */ public Accounts(Integer account, Users users, Double balance) { this.account = account; this.users = users; this.balance = balance; } // Property accessors @Id @Column(name = "account", unique = true, nullable = false) public Integer getAccount() { return this.account; } public void setAccount(Integer account) { this.account = account; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "usersId") public Users getUsers() { return this.users; } public void setUsers(Users users) { this.users = users; } @Column(name = "balance", precision = 22, scale = 0) public Double getBalance() { return this.balance; } public void setBalance(Double balance) { this.balance = balance; } } 5.2 DAO接口 package cn.edu.xupt.accounts; import java.util.List; /** * Interface for AccountsDAO. * * @author MyEclipse Persistence Tools */ public interface IAccountsDAO { /** * Perform an initial save of a previously unsaved Accounts entity. All * subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * IAccountsDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Accounts entity to persist * @throws RuntimeException * when the operation fails */ public void save(Accounts entity); /** * Delete a persistent Accounts entity. This operation must be performed * within the a database transaction context for the entity's data to be * permanently deleted from the persistence store, i.e., database. This * method uses the {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * IAccountsDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Accounts entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Accounts entity); /** * Persist a previously saved Accounts entity and return it or a copy of it * to the sender. A copy of the Accounts entity parameter is returned when * the JPA persistence mechanism has not previously been tracking the * updated entity. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = IAccountsDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Accounts entity to update * @return Accounts the persisted Accounts entity instance, may not be the * same * @throws RuntimeException * if the operation fails */ public Accounts update(Accounts entity); public Accounts findById(Integer id); /** * Find all Accounts entities with a specific property value. * * @param propertyName * the name of the Accounts property to query * @param value * the property value to match * @return List<Accounts> found by query */ public List<Accounts> findByProperty(String propertyName, Object value); public List<Accounts> findByBalance(Object balance); /** * Find all Accounts entities. * * @return List<Accounts> all Accounts entities */ public List<Accounts> findAll(); } 5.3 DAO类 package cn.edu.xupt.accounts; import java.util.List; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.Query; import cn.edu.xupt.ordersDetails.EntityManagerHelper; /** * A data access object (DAO) providing persistence and search support for * Accounts entities. Transaction control of the save(), update() and delete() * operations must be handled externally by senders of these methods or must be * manually added to each of these methods for data to be persisted to the JPA * datastore. * * @see cn.edu.xupt.accounts.Accounts * @author MyEclipse Persistence Tools */ public class AccountsDAO implements IAccountsDAO { // property constants public static final String BALANCE = "balance"; private EntityManager getEntityManager() { return EntityManagerHelper.getEntityManager(); } /** * Perform an initial save of a previously unsaved Accounts entity. All * subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * AccountsDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Accounts entity to persist * @throws RuntimeException * when the operation fails */ public void save(Accounts entity) { EntityManagerHelper.log("saving Accounts instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); em.persist(entity); em.flush(); em.getTransaction().commit(); } catch (RuntimeException re) { EntityManagerHelper.log("save failed", Level.SEVERE, re); throw re; } } /** * Delete a persistent Accounts entity. This operation must be performed * within the a database transaction context for the entity's data to be * permanently deleted from the persistence store, i.e., database. This * method uses the {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * AccountsDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Accounts entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Accounts entity) { EntityManagerHelper.log("deleting Accounts instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); entity = em.getReference(Accounts.class,entity.getAccount()); em.remove(entity); em.getTransaction().commit(); EntityManagerHelper.log("delete successful", Level.INFO, null); } catch (RuntimeException re) { EntityManagerHelper.log("delete failed", Level.SEVERE, re); throw re; } } /** * Persist a previously saved Accounts entity and return it or a copy of it * to the sender. A copy of the Accounts entity parameter is returned when * the JPA persistence mechanism has not previously been tracking the * updated entity. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = AccountsDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Accounts entity to update * @return Accounts the persisted Accounts entity instance, may not be the * same * @throws RuntimeException * if the operation fails */ public Accounts update(Accounts entity) { EntityManagerHelper.log("updating Accounts instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); Accounts result = getEntityManager().merge(entity); em.getTransaction().commit(); EntityManagerHelper.log("update successful", Level.INFO, null); return result; } catch (RuntimeException re) { EntityManagerHelper.log("update failed", Level.SEVERE, re); throw re; } } public Accounts findById(Integer id) { EntityManagerHelper.log("finding Accounts instance with id: " + id, Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); Accounts instance =em.find(Accounts.class, id); em.getTransaction().commit(); return instance; } catch (RuntimeException re) { EntityManagerHelper.log("find failed", Level.SEVERE, re); throw re; } } /** * Find all Accounts entities with a specific property value. * * @param propertyName * the name of the Accounts property to query * @param value * the property value to match * @return List<Accounts> found by query */ @SuppressWarnings("unchecked") public List<Accounts> findByProperty(String propertyName, final Object value) { EntityManagerHelper.log("finding Accounts instance with property: " + propertyName + ", value: " + value, Level.INFO, null); try { final String queryString = "select model from Accounts model where model." + propertyName + "= :propertyValue"; Query query = getEntityManager().createQuery(queryString); query.setParameter("propertyValue", value); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find by property name failed", Level.SEVERE, re); throw re; } } public List<Accounts> findByBalance(Object balance) { return findByProperty(BALANCE, balance); } /** * Find all Accounts entities. * * @return List<Accounts> all Accounts entities */ @SuppressWarnings("unchecked") public List<Accounts> findAll() { EntityManagerHelper.log("finding all Accounts instances", Level.INFO, null); try { final String queryString = "select model from Accounts model"; Query query = getEntityManager().createQuery(queryString); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find all failed", Level.SEVERE, re); throw re; } } } 六、库存管理 6.1 实体类 package cn.edu.xupt.orders; import java.sql.Timestamp; 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 cn.edu.xupt.users.Users; /** * Orders entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "orders", catalog = "wsy") public class Orders implements java.io.Serializable { // Fields private Integer ordersId; private Users users; private Timestamp time; // Constructors /** default constructor */ public Orders() { } /** minimal constructor */ public Orders(Integer ordersId) { this.ordersId = ordersId; } /** full constructor */ public Orders(Integer ordersId, Users users, Timestamp time) { this.ordersId = ordersId; this.users = users; this.time = time; } // Property accessors @Id @Column(name = "ordersId", unique = true, nullable = false) public Integer getOrdersId() { return this.ordersId; } public void setOrdersId(Integer ordersId) { this.ordersId = ordersId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "usersId") public Users getUsers() { return this.users; } public void setUsers(Users users) { this.users = users; } @Column(name = "time", length = 19) public Timestamp getTime() { return this.time; } public void setTime(Timestamp time) { this.time = time; } } 6.2 DAO接口 package cn.edu.xupt.orders; import java.sql.Timestamp; import java.util.List; /** * Interface for OrdersDAO. * * @author MyEclipse Persistence Tools */ public interface IOrdersDAO { /** * Perform an initial save of a previously unsaved Orders entity. All * subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * IOrdersDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Orders entity to persist * @throws RuntimeException * when the operation fails */ public void save(Orders entity); /** * Delete a persistent Orders entity. This operation must be performed * within the a database transaction context for the entity's data to be * permanently deleted from the persistence store, i.e., database. This * method uses the {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * IOrdersDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Orders entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Orders entity); /** * Persist a previously saved Orders entity and return it or a copy of it to * the sender. A copy of the Orders entity parameter is returned when the * JPA persistence mechanism has not previously been tracking the updated * entity. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = IOrdersDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Orders entity to update * @return Orders the persisted Orders entity instance, may not be the same * @throws RuntimeException * if the operation fails */ public Orders update(Orders entity); public Orders findById(Integer id); /** * Find all Orders entities with a specific property value. * * @param propertyName * the name of the Orders property to query * @param value * the property value to match * @return List<Orders> found by query */ public List<Orders> findByProperty(String propertyName, Object value); /** * Find all Orders entities. * * @return List<Orders> all Orders entities */ public List<Orders> findAll(); } 6.3 DAO实现 package cn.edu.xupt.orders; import java.sql.Timestamp; import java.util.List; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.Query; import cn.edu.xupt.ordersDetails.EntityManagerHelper; /** * A data access object (DAO) providing persistence and search support for * Orders entities. Transaction control of the save(), update() and delete() * operations must be handled externally by senders of these methods or must be * manually added to each of these methods for data to be persisted to the JPA * datastore. * * @see cn.edu.xupt.orders.Orders * @author MyEclipse Persistence Tools */ public class OrdersDAO implements IOrdersDAO { // property constants private EntityManager getEntityManager() { return EntityManagerHelper.getEntityManager(); } /** * Perform an initial save of a previously unsaved Orders entity. All * subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * OrdersDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Orders entity to persist * @throws RuntimeException * when the operation fails */ public void save(Orders entity) { EntityManagerHelper.log("saving Orders instance", Level.INFO, null); try { getEntityManager().persist(entity); EntityManager em=getEntityManager(); em.getTransaction().begin(); em.persist(entity); em.flush(); em.getTransaction().commit(); } catch (RuntimeException re) { EntityManagerHelper.log("save failed", Level.SEVERE, re); throw re; } } /** * Delete a persistent Orders entity. This operation must be performed * within the a database transaction context for the entity's data to be * permanently deleted from the persistence store, i.e., database. This * method uses the {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * OrdersDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Orders entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Orders entity) { EntityManagerHelper.log("deleting Orders instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); entity = em.getReference(Orders.class, entity.getOrdersId()); em.remove(entity); em.getTransaction().commit(); EntityManagerHelper.log("delete successful", Level.INFO, null); } catch (RuntimeException re) { EntityManagerHelper.log("delete failed", Level.SEVERE, re); throw re; } } /** * Persist a previously saved Orders entity and return it or a copy of it to * the sender. A copy of the Orders entity parameter is returned when the * JPA persistence mechanism has not previously been tracking the updated * entity. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = OrdersDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Orders entity to update * @return Orders the persisted Orders entity instance, may not be the same * @throws RuntimeException * if the operation fails */ public Orders update(Orders entity) { EntityManagerHelper.log("updating Orders instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); Orders result = getEntityManager().merge(entity); em.getTransaction().commit(); EntityManagerHelper.log("update successful", Level.INFO, null); return result; } catch (RuntimeException re) { EntityManagerHelper.log("update failed", Level.SEVERE, re); throw re; } } public Orders findById(Integer id) { EntityManagerHelper.log("finding Orders instance with id: " + id, Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); Orders instance =em.find(Orders.class, id); em.getTransaction().commit(); return instance; } catch (RuntimeException re) { EntityManagerHelper.log("find failed", Level.SEVERE, re); throw re; } } /** * Find all Orders entities with a specific property value. * * @param propertyName * the name of the Orders property to query * @param value * the property value to match * @return List<Orders> found by query */ @SuppressWarnings("unchecked") public List<Orders> findByProperty(String propertyName, final Object value) { EntityManagerHelper.log("finding Orders instance with property: " + propertyName + ", value: " + value, Level.INFO, null); try { final String queryString = "select model from Orders model where model." + propertyName + "= :propertyValue"; Query query = getEntityManager().createQuery(queryString); query.setParameter("propertyValue", value); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find by property name failed", Level.SEVERE, re); throw re; } } /** * Find all Orders entities. * * @return List<Orders> all Orders entities */ @SuppressWarnings("unchecked") public List<Orders> findAll() { EntityManagerHelper.log("finding all Orders instances", Level.INFO, null); try { final String queryString = "select model from Orders model"; Query query = getEntityManager().createQuery(queryString); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find all failed", Level.SEVERE, re); throw re; } } } 七、商品管理 7.1 实体类 package cn.edu.xupt.goodsInformation; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Goodsinformation entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "goodsinformation", catalog = "wsy") public class Goodsinformation implements java.io.Serializable { // Fields private Integer goodsId; private String goodsName; private Integer goodsNum; private Double goodsPrice; // Constructors /** default constructor */ public Goodsinformation() { } /** minimal constructor */ public Goodsinformation(Integer goodsId) { this.goodsId = goodsId; } /** full constructor */ public Goodsinformation(Integer goodsId, String goodsName, Integer goodsNum, Double goodsPrice) { this.goodsId = goodsId; this.goodsName = goodsName; this.goodsNum = goodsNum; this.goodsPrice = goodsPrice; } // Property accessors @Id @Column(name = "goodsId", unique = true, nullable = false) public Integer getGoodsId() { return this.goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } @Column(name = "goodsName", length = 16) public String getGoodsName() { return this.goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } @Column(name = "goodsNum") public Integer getGoodsNum() { return this.goodsNum; } public void setGoodsNum(Integer goodsNum) { this.goodsNum = goodsNum; } @Column(name = "goodsPrice", precision = 22, scale = 0) public Double getGoodsPrice() { return this.goodsPrice; } public void setGoodsPrice(Double goodsPrice) { this.goodsPrice = goodsPrice; } } 7.2 DAO接口 package cn.edu.xupt.goodsInformation; import java.util.List; /** * Interface for GoodsinformationDAO. * * @author MyEclipse Persistence Tools */ public interface IGoodsinformationDAO { /** * Perform an initial save of a previously unsaved Goodsinformation entity. * All subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * IGoodsinformationDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Goodsinformation entity to persist * @throws RuntimeException * when the operation fails */ public void save(Goodsinformation entity); /** * Delete a persistent Goodsinformation entity. This operation must be * performed within the a database transaction context for the entity's data * to be permanently deleted from the persistence store, i.e., database. * This method uses the * {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * IGoodsinformationDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Goodsinformation entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Goodsinformation entity); /** * Persist a previously saved Goodsinformation entity and return it or a * copy of it to the sender. A copy of the Goodsinformation entity parameter * is returned when the JPA persistence mechanism has not previously been * tracking the updated entity. This operation must be performed within the * a database transaction context for the entity's data to be permanently * saved to the persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = IGoodsinformationDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Goodsinformation entity to update * @return Goodsinformation the persisted Goodsinformation entity instance, * may not be the same * @throws RuntimeException * if the operation fails */ public Goodsinformation update(Goodsinformation entity); public Goodsinformation findById(Integer id); /** * Find all Goodsinformation entities with a specific property value. * * @param propertyName * the name of the Goodsinformation property to query * @param value * the property value to match * @return List<Goodsinformation> found by query */ public List<Goodsinformation> findByProperty(String propertyName, Object value); public List<Goodsinformation> findByGoodsName(Object goodsName); public List<Goodsinformation> findByGoodsNum(Object goodsNum); public List<Goodsinformation> findByGoodsPrice(Object goodsPrice); /** * Find all Goodsinformation entities. * * @return List<Goodsinformation> all Goodsinformation entities */ public List<Goodsinformation> findAll(); } 7.3 DAO实现 package cn.edu.xupt.goodsInformation; import java.util.List; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.Query; import cn.edu.xupt.ordersDetails.EntityManagerHelper; /** * A data access object (DAO) providing persistence and search support for * Goodsinformation entities. Transaction control of the save(), update() and * delete() operations must be handled externally by senders of these methods or * must be manually added to each of these methods for data to be persisted to * the JPA datastore. * * @see cn.edu.xupt.goodsInformation.Goodsinformation * @author MyEclipse Persistence Tools */ public class GoodsinformationDAO implements IGoodsinformationDAO { // property constants public static final String GOODS_NAME = "goodsName"; public static final String GOODS_NUM = "goodsNum"; public static final String GOODS_PRICE = "goodsPrice"; public static final String GOODS_ID = "goodsId"; private EntityManager getEntityManager() { return EntityManagerHelper.getEntityManager(); } /** * Perform an initial save of a previously unsaved Goodsinformation entity. * All subsequent persist actions of this entity should use the #update() * method. This operation must be performed within the a database * transaction context for the entity's data to be permanently saved to the * persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#persist(Object) * EntityManager#persist} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * GoodsinformationDAO.save(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Goodsinformation entity to persist * @throws RuntimeException * when the operation fails */ public void save(Goodsinformation entity) { EntityManagerHelper.log("saving Goodsinformation instance", Level.INFO, null); try { getEntityManager().persist(entity); EntityManager em=getEntityManager(); em.getTransaction().begin(); em.persist(entity); em.flush(); em.getTransaction().commit(); } catch (RuntimeException re) { EntityManagerHelper.log("save failed", Level.SEVERE, re); throw re; } } /** * Delete a persistent Goodsinformation entity. This operation must be * performed within the a database transaction context for the entity's data * to be permanently deleted from the persistence store, i.e., database. * This method uses the * {@link javax.persistence.EntityManager#remove(Object) * EntityManager#delete} operation. * * <pre> * EntityManagerHelper.beginTransaction(); * GoodsinformationDAO.delete(entity); * EntityManagerHelper.commit(); * entity = null; * </pre> * * @param entity * Goodsinformation entity to delete * @throws RuntimeException * when the operation fails */ public void delete(Goodsinformation entity) { EntityManagerHelper.log("deleting Goodsinformation instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); entity = em.getReference(Goodsinformation.class,entity.getGoodsId()); em.remove(entity); em.getTransaction().commit(); EntityManagerHelper.log("delete successful", Level.INFO, null); } catch (RuntimeException re) { EntityManagerHelper.log("delete failed", Level.SEVERE, re); throw re; } } /** * Persist a previously saved Goodsinformation entity and return it or a * copy of it to the sender. A copy of the Goodsinformation entity parameter * is returned when the JPA persistence mechanism has not previously been * tracking the updated entity. This operation must be performed within the * a database transaction context for the entity's data to be permanently * saved to the persistence store, i.e., database. This method uses the * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge} * operation. * * <pre> * EntityManagerHelper.beginTransaction(); * entity = GoodsinformationDAO.update(entity); * EntityManagerHelper.commit(); * </pre> * * @param entity * Goodsinformation entity to update * @return Goodsinformation the persisted Goodsinformation entity instance, * may not be the same * @throws RuntimeException * if the operation fails */ public Goodsinformation update(Goodsinformation entity) { EntityManagerHelper.log("updating Goodsinformation instance", Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); Goodsinformation result = getEntityManager().merge(entity); em.getTransaction().commit(); EntityManagerHelper.log("update successful", Level.INFO, null); return result; } catch (RuntimeException re) { EntityManagerHelper.log("update failed", Level.SEVERE, re); throw re; } } public Goodsinformation findById(Integer id) { EntityManagerHelper.log("finding Goodsinformation instance with id: " + id, Level.INFO, null); try { EntityManager em=getEntityManager(); em.getTransaction().begin(); Goodsinformation instance =em.find(Goodsinformation.class, id); em.getTransaction().commit(); return instance; } catch (RuntimeException re) { EntityManagerHelper.log("find failed", Level.SEVERE, re); throw re; } } /** * Find all Goodsinformation entities with a specific property value. * * @param propertyName * the name of the Goodsinformation property to query * @param value * the property value to match * @return List<Goodsinformation> found by query */ @SuppressWarnings("unchecked") public List<Goodsinformation> findByProperty(String propertyName, final Object value) { EntityManagerHelper.log( "finding Goodsinformation instance with property: " + propertyName + ", value: " + value, Level.INFO, null); try { final String queryString = "select model from Goodsinformation model where model." + propertyName + "= :propertyValue"; Query query = getEntityManager().createQuery(queryString); query.setParameter("propertyValue", value); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find by property name failed", Level.SEVERE, re); throw re; } } public List<Goodsinformation> findByGoodsName(Object goodsName) { return findByProperty(GOODS_NAME, goodsName); } public List<Goodsinformation> findByGoodsNum(Object goodsNum) { return findByProperty(GOODS_NUM, goodsNum); } public List<Goodsinformation> findByGoodsPrice(Object goodsPrice) { return findByProperty(GOODS_PRICE, goodsPrice); } /** * Find all Goodsinformation entities. * * @return List<Goodsinformation> all Goodsinformation entities */ @SuppressWarnings("unchecked") public List<Goodsinformation> findAll() { EntityManagerHelper.log("finding all Goodsinformation instances", Level.INFO, null); try { final String queryString = "select model from Goodsinformation model"; Query query = getEntityManager().createQuery(queryString); return query.getResultList(); } catch (RuntimeException re) { EntityManagerHelper.log("find all failed", Level.SEVERE, re); throw re; } } } 八、系统首页 8.1 核心程序 <div data-options="region:'west',title:'系统菜单',split:true" style="width:200px;"> <div id="aa" class="easyui-accordion" data-options="fit:true" style="width:300px;height:200px;"> <div title="系统管理" data-options="" style="overflow:auto;padding:10px;"> <ul> <li><a href="#" title="<%=request.getContextPath() %>/user/select.do">用户管理</a></li> <li><a href="#" title="<%=request.getContextPath() %>/product/select.do">商品管理</a></li> <li><a href="#" title="<%=request.getContextPath() %>/orders/select.do">订单管理</a></li> </ul> </div> <div title="库存管理" data-options="" style="padding:10px;"> <ul> <li><a href="#" title="<%=request.getContextPath() %>/inventory/in.do">入库管理</a></li> <li><a href="#" title="<%=request.getContextPath() %>/inventory/query.do">库存查询</a></li> </ul> </div> </div> </div>
06-25
### 系统架构设计 开发一个基于 Spring MVC JPA 的电子商务后台管理系统,可以采用典型的分层架构模式,包括表现层(前端)、业务逻辑层数据访问层。整体结构如下: - **表现层**:使用 HTML、CSS JavaScript 技术构建用户界面,同结合 Thymeleaf 模板引擎与后端进行动态数据交互。 - **业务逻辑层**:采用 Spring MVC 框架处理业务逻辑,如订单管理、商品信息维护等[^1]。 - **数据访问层**:利用 JPA(Java Persistence API)实现对数据库的持久化操作,支持 ORM 映射数据库事务管理。 ### 数据库设计 系统需要创建多个核心表来支持主要功能模块,包括但不限于以下表格: - **用户表**:包含字段如 `user_id`、`username`、`password`、`contact_info` 等,用于存储用户的基本信息。 - **商品表**:包含 `product_id`、`product_name`、`price`、`stock`、`origin` 等字段,记录商品的相关属性。 - **订单表**:包括 `order_id`、`user_id`、`product_id`、`quantity`、`status` 等字段,跟踪订单状态及关联信息。 - **权限表**:通过角色分配权限,例如管理员可访问所有模块,而普通用户仅能查看特定内容。 ### 功能模块 #### 用户管理 该模块负责用户的注册、登录、修改个人信息以及删除账户等功能。为了确保安全性,密码应以加密形式存储在数据库中,并且登录过程中使用 HTTPS 协议传输敏感信息[^1]。 #### 商品管理 提供商品信息的增删改查功能。管理员可以通过界面添加新商品、更新现有商品信息或删除不再销售的商品。此模块需确保数据的一致性完整性,防止 SQL 注入攻击。 #### 库存查询 允许用户查看当前库存情况,支持按商品名称、类别等多种条件筛选。对于库存不足的商品,系统可自动发出预警提示。 #### 权限管理 实现基于角色的访问控制(RBAC),不同角色拥有不同的操作权限。例如,管理员可以执行所有操作,而普通员工只能查看部分数据或执行有限的操作。 ### 安全性设计 为保障系统的安全性,采取以下措施: - 使用 HTTPS 加密通信,保护数据传输过程中的隐私。 - 对用户密码进行加密存储,推荐使用 BCrypt 箉法。 - 防止 SQL 注入 XSS 攻击,输入验证输出编码是关键手段。 - 实现细粒度的权限控制系统,确保每个用户只能访问其被授权的内容[^1]。 ### 代码实现步骤 1. 创建 Maven 项目并配置依赖项,包括 Spring Boot Starter Web、Spring Data JPA、Thymeleaf 等。 2. 设计实体类,定义与数据库表对应的 Java 类。 3. 编写 Repository 接口,继承 JpaRepository 接口以获得基本的 CRUD 方法。 4. 开发 Service 层,编写业务逻辑代码。 5. 构建 Controller 层,处理 HTTP 请求并调用相应的服务方法。 6. 制作前端页面,使用 Thymeleaf 渲染视图。 7. 测试各个模块的功能,确保无误后再部署到生产环境。 ### 示例代码 #### 实体类 - User.java ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; // Getters and Setters } ``` #### Repository 接口 - UserRepository.java ```java public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUsername(String username); } ``` #### Service 层 - UserService.java ```java @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public void saveUser(User user) { userRepository.save(user); } } ``` #### Controller 层 - UserController.java ```java @Controller @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public String listUsers(Model model) { model.addAttribute("users", userService.getAllUsers()); return "user-list"; } @PostMapping public String createUser(@ModelAttribute("user") User user) { userService.saveUser(user); return "redirect:/users"; } } ``` #### 前端页面 - user-list.html (Thymeleaf) ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User List</title> </head> <body> <h1>Users</h1> <table border="1"> <tr> <th>ID</th> <th>Username</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.username}"></td> </tr> </table> </body> </html> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值