技术标签: hbm2java maven
一、数据库准备
1.创建数据库maven
create database maven character set utf8 collate utf8_general_ci; //use maven;
2.创建用户表
create table t_users(
id int primary key auto_increment,
username varchar(30) not null,
password varchar(50) not null,
constraint unq_users_username unique(username)
);
3.插入测试数据
insert into t_users(username,password) values('admin', md5('admin'));
insert into t_users(username,password) values('user', md5('user'));
二、项目框架构建
1.创建简单父工程maven-parent,注意packaging类型为pom
2.复制prom.xml内容以引入jar包
3.创建子工程(Maven Module)maven-entity,注意packaging类型为jar,选择父类型为maven-parent
4.创建子工程(Maven Module)maven-utils,注意packaging类型为jar,选择父类型为maven-parent
5.创建子工程(Maven Module)maven-dao,注意packaging类型为jar,选择父类型为maven-parent
6.创建子工程(Maven Module)maven-service,注意packaging类型为jar,选择父类型为maven-parent
7.创建子工程(Maven Module)maven-web,,注意packaging类型为war,选择父类型为maven-parent
8.将maven-parent发布到本地仓库,maven会自动将所有子工程发布到本地仓库
9.按顺序为各个子项目添加依赖关系,具体依赖顺序如下 web--->service-->dao--->utils--->entity
10.在子工程之间添加依赖的具体操作如下:
10.1 发布工程后,最好先打开Maven Repository重建一下索引
10.2 打开maven-utils子工程的porm.xml,选择dependencies标签添加对maven-entity的依赖(也可以直接编辑porm.xml源码添加)
10.3 打开maven-dao子工程的porm.xml,选择dependencies标签添加对maven-utils的依赖(也可以直接编辑porm.xml源码添加)
10.4 打开maven-service子工程的porm.xml,选择dependencies标签添加对maven-dao的依赖(也可以直接编辑porm.xml源码添加)
10.5 打开maven-web子工程的porm.xml,选择dependencies标签添加对maven-web的依赖(也可以直接编辑porm.xml源码添加)
11.子工程之间的依赖会以工程的形式出现在lib中,若关闭某一子工程,则会变为以jar方式引入
12.在maven-web工程的webapp创建WEB-INF目录及web.xml文件
三、构建maven-entity子工程
1.在src/main/java的com.hao.entity下编写User.java,并采用Hibernate注解映射实体
package com.hao.entity;
// Generated 2017-8-6 12:57:28 by Hibernate Tools 4.0.0
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;
import javax.persistence.UniqueConstraint;
/**
* TUsers generated by hbm2java
*/
@Entity
@Table(name = "t_users", catalog = "maven", uniqueConstraints = @UniqueConstraint(columnNames = "username"))
public class User implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@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 = "username", unique = true, nullable = false, length = 30)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password", nullable = false, length = 50)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
四、构建maven-utils子工程
1.在src/main/java下编写MD5工具类,用于密码加密
package com.hao.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
/**
* 使用md5的算法进行加密
*/
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
public static void main(String[] args) {
System.out.println(md5("123"));
}
}
五、构建maven-dao子工程
1.在src/main/java下进行BaseDao的抽取以及UserDao代码的编写
1.1 BaseDao接口
package com.hao.dao.base;
import java.io.Serializable;
import java.util.List;
public interface BaseDao {
void save(T entity);
void delete(T entity);
void deleteById(Serializable id);
void update(T entity);
T findById(Serializable id);
List findAll();
}
1.2 BaseDaoImpl实现类
package com.hao.dao.base.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.hao.dao.base.BaseDao;
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
private Class entityClass;
@SuppressWarnings("unchecked")
public BaseDaoImpl() {
// 获取子类对象的父类类型
ParameterizedType superClass = (ParameterizedType) this.getClass()
.getGenericSuperclass();
// 获得在父类类型上声明的反省数组
Type[] genericTypes = superClass.getActualTypeArguments();
// 第一个泛型即为实体类型
entityClass = (Class) genericTypes[0];
}
@Override
public void save(T entity) {
getHibernateTemplate().save(entity);
}
@Override
public void delete(T entity) {
getHibernateTemplate().delete(entity);
}
@Override
public void deleteById(Serializable id) {
T entity = getHibernateTemplate().load(entityClass, id);
getHibernateTemplate().delete(entity);
}
@Override
public void update(T entity) {
getHibernateTemplate().update(entity);
}
@Override
public T findById(Serializable id) {
return getHibernateTemplate().get(entityClass, id);
}
@Override
public List findAll() {
return getHibernateTemplate().loadAll(entityClass);
}
/**
* HibernateDao接口在使用前必须注入SessionFactory
*
* @param sessionFactory
*/
@Autowired
public void setSF(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
}
1.3 UserDao接口
package com.hao.dao;
import com.hao.dao.base.BaseDao;
import com.hao.entity.User;
public interface UserDao extends BaseDao {
User login(String username, String password);
}
1.4 UserDaoImpl实现类
package com.hao.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.hao.dao.UserDao;
import com.hao.dao.base.impl.BaseDaoImpl;
import com.hao.entity.User;
@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
@Override
public User login(String username, String password) {
@SuppressWarnings("unchecked")
List user = (List) getHibernateTemplate().find(
"from User u where u.username=? and u.password=?", username,
password);
if (user == null || user.size() < 1) {
return null;
} else {
return user.get(0);
}
}
}
2.在src/main/resources下创建applicationContext-dao.xml文件,编写属于dao层的内容
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
org.hibernate.dialect.MySQLDialect
true
true
update
3.在src/main/resources下创建db.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/maven
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=h66666
4.在src/main/resources下创建log4j.properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=D:\\temp\\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### fatal error warn info debug debug trace
log4j.rootLogger=debug, stdout
#log4j.logger.org.hibernate=INFO
#log4j.logger.org.hibernate.type=INFO
5.为了在Dao层能对save,update之类的方法进行测试,还需而外提供Service层中的Spring声明式事务配置
6.故在src/test/resources下创建applicationContext-daotest.xml,提供和事务相关的配置(最好与applicationContext-service中的事务配置保持一致)
7.执行单元测试时,实际上需要使用到多个applicationContext文件,其中applicationContext-daotest.xml就是在src/test/resources中定义的
8.单元测试依赖多个applicationContext文件时,要在@ContextConfiguration的locations中列举出来
9.在src/test/java的com.hao.dao包下编写Dao层单元测试代码,注意要添加@Transaction注解
package com.hao.dao;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.hao.entity.User;
import com.hao.utils.MD5Utils;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-dao.xml",
"classpath:applicationContext-daotest.xml" })
@Transactional
public class UserDaoTest {
@Autowired
UserDao userDao;
@Test
public void testLogin() {
Assert.assertNotNull(userDao.login("admin", MD5Utils.md5("admin")));
Assert.assertNull(userDao.login("admin", MD5Utils.md5("pass")));
Assert.assertNotNull(userDao.login("user", MD5Utils.md5("user")));
System.out.println(userDao.login("admin", MD5Utils.md5("admin")));
}
@Test
public void testSave() {
User u = new User();
u.setUsername("dao");
u.setPassword("dao");
userDao.save(u);
}
}
六、构建maven-service子工程
1.在src/main/java下编写UserService相关代码
1.1 UserService接口
package com.hao.service;
import com.hao.entity.User;
public interface UserService {
User login(User user);
void save(User user);
}
1.2 UserServiceImpl实现类
package com.hao.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.hao.dao.UserDao;
import com.hao.entity.User;
import com.hao.service.UserService;
import com.hao.utils.MD5Utils;
@Service("userService")
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public User login(User user) {
String pass = MD5Utils.md5(user.getPassword());
return userDao.login(user.getUsername(), pass);
}
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
public void save(User user) {
userDao.save(user);
}
}
2.在src/main/resources下创建applicationContext-service.xml,编写service层相关的配置(主要是声明式事务的配置)
3.多个applicationContext也可以采用通配符方式配置,如"classpath*:applicationContext-*.xml",但不建议
4.因为使用通配符方式时,我在eclipse能成功执行单元测试,但使用maven的install命令发布到本地仓库时,单元测试代码会执行失败
5.出错原因为为dao子工程的applicationContext找不到,因此建议使用列举文件方式而不要采用通配符的方式
6.注意,第一个通配符表示读取包括类路径和jar包下的径的配置文件
7.在对Service进行单元测试时,可添加@Transactional避免脏数据的产生,否则会使用service方法中配置的事务,会产生脏数据
8.在src/test/java下编写Service层的单元测试代码
package com.hao.service;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.hao.entity.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:applicationContext-dao.xml", "classpath:applicationContext-service.xml"})
@Transactional
public class UserServiceTest {
@Autowired
UserService userService;
@Test
public void testLogin() {
User u1 = new User();
u1.setUsername("admin");
u1.setPassword("admin");
User u2 = new User();
u2.setUsername("admin");
u2.setPassword("pass");
User u3 = new User();
u3.setUsername("user");
u3.setPassword("user");
Assert.assertNotNull(userService.login(u1));
Assert.assertNull(userService.login(u2));
Assert.assertNotNull(userService.login(u3));
}
@Test
public void testSave() {
User u = new User();
u.setUsername("service");
u.setPassword("service");
userService.save(u);
}
}
七、构建maven-web子工程
1.action的抽取以及UserAction的编写
1.1 抽取BaseAction
package com.hao.action.base;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class BaseAction extends ActionSupport implements ModelDriven,
RequestAware, SessionAware {
private static final long serialVersionUID = 1L;
protected Map request;
protected Map session;
protected T model;
@Override
public void setRequest(Map request) {
this.request = request;
}
@Override
public void setSession(Map session) {
this.session = session;
}
@Override
public T getModel() {
return model;
}
public BaseAction() {
// 获取父类
ParameterizedType genericSuperclass = (ParameterizedType) this
.getClass().getGenericSuperclass();
// 获取父类的泛型数组
Type[] types = genericSuperclass.getActualTypeArguments();
// 取得第一个泛型,即Model的类型
@SuppressWarnings("unchecked")
Class entityClass = (Class) types[0];
try {
model = entityClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
1.2 UserAction代码编写,注意scope要为prototype
package com.hao.action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.hao.action.base.BaseAction;
import com.hao.entity.User;
import com.hao.service.UserService;
@Controller("userAction")
@Scope("prototype")
public class UserAction extends BaseAction {
private static final long serialVersionUID = 1L;
public String login() {
System.out.println("-------------------------------------------------------"
+ this + "-------------------------------------------------------");
User user = userService.login(model);
if (user == null) {
request.put("errorInfo", "用户名或密码错误");
return LOGIN;
}
session.put("loginUser", user);
return SUCCESS;
}
@Autowired
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
2.在struts.xml中配置struts,整合spring
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
/success.jsp
/index.jsp
3.在web.xml中配置spring监听器,让spring容器随web项目启动而启动
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath*:applicationContext-*.xml
4.配置过滤器,用于扩展Hibernate Session的作用域知道请求结束,注意一定要配置在struts2过滤器之前
openSessionInView
org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
openSessionInView
/*
5.配置struts2过滤器
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
八、编写页面,启动项目
1.index.jsp,注意引入jstl标签库
用户名:
密 码:
2.success.jsp
3.使用tomcat7:run命令运行或者使用eclipse从执行服务器运行,访问index.jsp测试即可
文章浏览阅读68次。郑重声明:此文为转载来的,出处已不知了,侵告删。 在讲Web Service开发服务时,需要介绍一个目前开发Web Service的几个框架,分别为Axis,axis2,Xfire,CXF以及JWS(也就是前面所述的JAX-WS,这是Java6发布所提供的对 Web Service服务的一种实现。)前面几项都为开源项目,而其中又以axis2与cxf所最为常用,Axis与XFir..._java开发使用的几种server的名称
文章浏览阅读1.4k次。一、前言 C/C++的编译过程包含了四个步骤: 1. 预处理(Preprocessing) 2. 编译(Compilation) 3. 汇编(Assemble) 4..链接(Linking)二、预处理 预处理阶段主要处理一些预处理指令,比如文件包括、宏定义、条件编译。1.文件包括 文件包括就是将所有的#include..._怎么在devc++里面把c文件变成汇编语言
文章浏览阅读837次,点赞3次,收藏9次。B站 刘二大人 传送门 循环神经网络(基础篇)课件链接:https://pan.baidu.com/s/1vZ27gKp8Pl-qICn_p2PaSw提取码:cxe4模型还是将输入“hello”训练输出为“ohlol”,用LSTM网络实现。按照计算图实现LSTM之后,又尝试了加入embedding的方法。加embedding的训练快,但是我的LSTM效果不如前面RNN的,不知道是我网络写的有问题还是怎么回事。LSTM的网络结构示意图和公式:根据我自己的理解写出来的LSTM模型,有不对的地方_pytorch深度学习实践12课后作业
文章浏览阅读208次。Android课程设计报告院 系: 计算机与信息工程学院班 级: 10级软件技术一班学 号:姓 名:PAGEPAGE 14目录TOC \o "1-3" \h \u 24017 一、系统架构 311293 二、功能分配 35248 2.1.浏览功能 326351 2.2.查询功能 314154 2.3.插入功能 328656 2.4.修改功能 41740 2.5.删除功能 41540 三、内..._android无线点餐系统
文章浏览阅读566次。安装方式一:如果使用的是PyCharm则File-->Settings-->Project Interpreter,选择绿色加号搜索Scrapy安装即可,如下图:这里需要注意Manage Repositories可以配置成: https://pypi.douban.com/simple/ http://mirrors.aliyun.com/pypi/simple/..._command "e:\python3.7.3\python.exe -u -c "import setuptools, tokenize;__file
文章浏览阅读471次。由于HTTP协议是无状态的协议,所以服务端需要记录用户的状态时,就需要用某种机制来识具体的用户,这个机制就是Session.典型的场景比如购物车,当你点击下单按钮时,由于HTTP协议无状态,所以并不知道是哪个用户操作的,所以服务端要为特定的用户创建了特定的Session,用用于标识这个用户,并且跟踪用户,这样才知道购物车里面有几本书。这个Session是保存在服务端的,有一个唯一标识。在服务端保..._cookie和session区别
文章浏览阅读1.4w次,点赞6次,收藏19次。参考:http://www.jq22.com/jquery-info6010使用方法Owl Carousel 2是上一版Owl Carousel的升级版本。Owl Carousel 2可以让你创建漂亮的响应式旋转木马的jQuery插件,它支持移动触摸屏,功能十分强大。Owl的新特性有: 可以无限循环 项目可以居中显示 灵活的速度控制 多级别的paddin..._owlcarousel
文章浏览阅读3.5k次。主要参考:官方网址:http://caffe.berkeleyvision.org/gathered/examples/imagenet.html数据集及第一部分参考网址:http://www.lxway.com/4010652262.htm主要步骤:1. 准备数据集2. 标记数据集3. 创建lmdb格式的数据4. 计算均值5. 设置网络及求解器6. 运行求解由于imagenet的数据集太大,博主..._caffenet
文章浏览阅读1.8k次,点赞5次,收藏12次。我写了一个简单的Demo项目,有需要的文末可获取项目github地址,该项目我会一直保持更新。基于quartz2.3.1实现动态管理定时任务。使用swagger实现接口文档。前后端统一使用JSON格式交互。使用Hutool工具类直接连接数据库,避免Job任务中不能使用Autowired问题。swagger文档如下图:后续文章创建JobDetail(JobBuilder详解)创建CronTrigger(TriggerBuilder详解)_springboot实现动态管理quartz
文章浏览阅读702次。一、Hibernate映射文件
文章浏览阅读2k次。重点在后面:https://blog.csdn.net/z_344791576/article/details/46328443?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522159546478119725219951536%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=15954647811972521995_c# 直接调用斑马打印机打印固定模板
文章浏览阅读926次。一. 二维图形(Two dimensional plotting)1. 基本绘图函数(Basic plotting function):Plot,semilogx,semilogy, loglog,polar, plotyy(1). 单矢量绘图(single vectorplotting):plot(y),矢量y的元素与y元素下标之间在线性坐标下的关系曲线。例1:单矢量绘图y=[0 0.6 2...._animatedline 添加图例