博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javaweb各种框架组合案例(三):maven+spring+springMVC+hibernate
阅读量:5897 次
发布时间:2019-06-19

本文共 19225 字,大约阅读时间需要 64 分钟。

1.hibernate译为“越冬”,指的是给java程序员带来春天,因为java程序员无需再关心各种sql了;

2.hibernate通过java类生成数据库表,通过操作对象来映射成SQL;

3.hibernate是真正意义上的ORM框架,因为他实现了对象(Object)---->关系(Relation)的映射(Mapping);

4.maven项目整体包结构(报错是eclipse发神经,不用管)

因为hibernate可以根据类生成表,所以只需创建数据库即可;

create database ssh;

 

该案例实现了一个用户拥有多部手机的关系

 

5.各种配置文件

(1)pom.xml

4.0.0
com.xiaog
testssh
0.0.1-SNAPSHOT
war
org.springframework
spring-webmvc
5.1.5.RELEASE
org.aspectj
aspectjrt
1.8.0
org.aspectj
aspectjweaver
1.8.0
org.springframework
spring-jdbc
5.1.5.RELEASE
mysql
mysql-connector-java
5.1.47
com.alibaba
druid
1.1.10
org.hibernate
hibernate-core
4.2.2.Final
org.springframework
spring-orm
4.2.4.RELEASE
ch.qos.logback
logback-classic
1.1.3
org.logback-extensions
logback-ext-spring
0.1.2
org.slf4j
jcl-over-slf4j
1.7.12
javax.servlet
servlet-api
3.0-alpha-1
provided
jstl
jstl
1.1.2
compile
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
1.8
UTF-8
org.apache.tomcat.maven
tomcat7-maven-plugin
2.1
9999
/testssh
UTF-8
testssh
tomcat7
pom.xml

 

(2)spring-context.xml

Spring公共配置
org.hibernate.dialect.MySQLDialect
true
false
update
spring-context.xml

 

 

 

(3)spring-mvc.xml

spring-mvc.xml

 

(4)logback.xml

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
 
 
 
  
logback.xml

 

(5)jdbc.properties

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/ssh?useSSL=false&useUnicode=true&characterEncoding=utf8jdbc.username=rootjdbc.password=root
jdbc.properties

 

(6)web.xml

testssh
contextConfigLocation
classpath:spring-context.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
spring-mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
spring-mvc
/
logbackConfigLocation
classpath:logback.xml
ch.qos.logback.ext.spring.web.LogbackConfigListener
index.jsp
web.xml

 

 

6.实体类User和Phone

package com.xiaog.entity;import java.util.List;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.OneToMany;import javax.persistence.Table;@Entity@Table(name="user")public class User {        @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    private Integer id;        private String username;        private String password;        @OneToMany(targetEntity=Phone.class)    @JoinColumn(name="user_id")    private List
phones;//一个用户拥有多部手机 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List
getPhones() { return phones; } public void setPhones(List
phones) { this.phones = phones; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", phones=" + phones + "]"; } }
User

 

package com.xiaog.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="phone")public class Phone {        @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    private Integer id;        private String brand;//品牌    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getBrand() {        return brand;    }    public void setBrand(String brand) {        this.brand = brand;    }    @Override    public String toString() {        return "Phone [id=" + id + ", brand=" + brand + "]";    }}
Phone

 

 

7.核心dao接口及其实现

package com.xiaog.core.dao;import java.util.List;public interface CoreDao
{ int insert(T t); int delete(int id); int update(T t); T getOne(int id); List
getList(T t); }
CoreDao
package com.xiaog.core.dao.impl;import java.lang.reflect.ParameterizedType;import java.util.List;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.orm.hibernate4.support.HibernateDaoSupport;import com.xiaog.core.dao.CoreDao;import com.xiaog.entity.User;//继承HibernateDaoSupport 可以直接使用CRUD操作public class CoreDaoImpl
extends HibernateDaoSupport implements CoreDao
{ private Class
clazz; private final static Logger logger = LoggerFactory.getLogger(CoreDaoImpl.class); @SuppressWarnings("unchecked") public CoreDaoImpl() { this.clazz = (Class
)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } @Override public int insert(T t) { return (int) super.getHibernateTemplate().save(t); } @Override public int delete(int id) { super.getHibernateTemplate().delete(new User() {
{setId(id);}}); return 1; } @Override public int update(T t) { super.getHibernateTemplate().update(t); return 1; } @Override public T getOne(int id) { return super.getHibernateTemplate().get(clazz, id); } @Override public List
getList(T t) { //logger.info("进入CoreDaoImpl......"); return super.getHibernateTemplate().findByExample(t); }}
CoreDaoImpl

 

 

8.模块dao接口及其实现(只需继承核心dao即可)

package com.xiaog.dao;import com.xiaog.core.dao.CoreDao;import com.xiaog.entity.User;public interface UserDao extends CoreDao
{}
UserDao
package com.xiaog.dao;import com.xiaog.core.dao.CoreDao;import com.xiaog.entity.Phone;public interface PhoneDao extends CoreDao
{}
PhoneDao

 

package com.xiaog.dao.impl;import org.springframework.stereotype.Repository;import com.xiaog.core.dao.impl.CoreDaoImpl;import com.xiaog.dao.UserDao;import com.xiaog.entity.User;@Repositorypublic class UserDaoImpl extends CoreDaoImpl
implements UserDao {}
UserDaoImpl
package com.xiaog.dao.impl;import org.springframework.stereotype.Repository;import com.xiaog.core.dao.impl.CoreDaoImpl;import com.xiaog.dao.PhoneDao;import com.xiaog.entity.Phone;@Repositorypublic class PhoneDaoImpl extends CoreDaoImpl
implements PhoneDao {}
PhoneDaoImpl

 

 

9.service接口及其实现

package com.xiaog.service;import com.xiaog.entity.User;public interface UserService {    User login(User user);}
UserService
package com.xiaog.service.impl;import java.util.List;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.xiaog.dao.UserDao;import com.xiaog.entity.User;import com.xiaog.service.UserService;@Servicepublic class UserServiceImpl implements UserService {    @Autowired    private UserDao userDao;        private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);        @Override    public User login(User user) {        //logger.info("进入UserServiceImpl......");        List
users = userDao.getList(user); logger.info("users="+users); if(users!=null&&users.size()>0) { return users.get(0); }else { return null; } }}
UserServiceImpl

 

 

10.controller

package com.xiaog.controller;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.xiaog.entity.User;import com.xiaog.service.UserService;@Controller@RequestMapping("/user")public class UserController {    @Autowired    private UserService userService;        private final static Logger logger = LoggerFactory.getLogger(UserController.class);        @RequestMapping(value = "/login",params= {"username","password","username!=","password!="})    public String login(Model model,User user) {        logger.info("user(request)="+user);        user = userService.login(user);        logger.info("user="+user);        model.addAttribute("user", user);        return "result";    }    }
UserController

 

 

11.jsp页面测试登录

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Insert title here
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
username=${user}
result.jsp

 

 

12.项目启动后,你会发现你的ssh数据库中多了两张表User和Phone,自己在插入几条数据

user表                                                 phone表

      

 

13.测试

index.jsp表单中输入1001和123

result.jsp

 

控制台打印

2019-06-22 09:40:24.477 [http-bio-9999-exec-9] INFO  com.xiaog.controller.UserController - user(request)=User [id=null, username=1002, password=456, phones=null]2019-06-22 09:40:24.519 [http-bio-9999-exec-9] DEBUG org.hibernate.SQL - select this_.id as id1_1_0_, this_.password as password2_1_0_, this_.username as username3_1_0_ from user this_ where (this_.password=? and this_.username=?)Hibernate: select this_.id as id1_1_0_, this_.password as password2_1_0_, this_.username as username3_1_0_ from user this_ where (this_.password=? and this_.username=?)2019-06-22 09:40:24.520 [http-bio-9999-exec-9] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - 4562019-06-22 09:40:24.520 [http-bio-9999-exec-9] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - 10022019-06-22 09:40:24.523 [http-bio-9999-exec-9] DEBUG org.hibernate.SQL - select phones0_.user_id as user3_1_1_, phones0_.id as id1_0_1_, phones0_.id as id1_0_0_, phones0_.brand as brand2_0_0_ from phone phones0_ where phones0_.user_id=?Hibernate: select phones0_.user_id as user3_1_1_, phones0_.id as id1_0_1_, phones0_.id as id1_0_0_, phones0_.brand as brand2_0_0_ from phone phones0_ where phones0_.user_id=?2019-06-22 09:40:24.524 [http-bio-9999-exec-9] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [INTEGER] - 22019-06-22 09:40:24.533 [http-bio-9999-exec-9] INFO  com.xiaog.service.impl.UserServiceImpl - users=[User [id=2, username=1002, password=456, phones=[Phone [id=3, brand=三星], Phone [id=4, brand=小米], Phone [id=5, brand=魅族]]]]2019-06-22 09:40:24.557 [http-bio-9999-exec-9] INFO  com.xiaog.controller.UserController - user=User [id=2, username=1002, password=456, phones=[Phone [id=3, brand=三星], Phone [id=4, brand=小米], Phone [id=5, brand=魅族]]]2019-06-22 10:38:09.540 [http-bio-9999-exec-5] INFO  com.xiaog.controller.UserController - user(request)=User [id=null, username=1001, password=123, phones=null]2019-06-22 10:38:09.549 [http-bio-9999-exec-5] DEBUG org.hibernate.SQL - select this_.id as id1_1_0_, this_.password as password2_1_0_, this_.username as username3_1_0_ from user this_ where (this_.password=? and this_.username=?)Hibernate: select this_.id as id1_1_0_, this_.password as password2_1_0_, this_.username as username3_1_0_ from user this_ where (this_.password=? and this_.username=?)2019-06-22 10:38:09.550 [http-bio-9999-exec-5] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - 1232019-06-22 10:38:09.550 [http-bio-9999-exec-5] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - 10012019-06-22 10:38:09.554 [http-bio-9999-exec-5] DEBUG org.hibernate.SQL - select phones0_.user_id as user3_1_1_, phones0_.id as id1_0_1_, phones0_.id as id1_0_0_, phones0_.brand as brand2_0_0_ from phone phones0_ where phones0_.user_id=?Hibernate: select phones0_.user_id as user3_1_1_, phones0_.id as id1_0_1_, phones0_.id as id1_0_0_, phones0_.brand as brand2_0_0_ from phone phones0_ where phones0_.user_id=?2019-06-22 10:38:09.556 [http-bio-9999-exec-5] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [INTEGER] - 12019-06-22 10:38:09.563 [http-bio-9999-exec-5] INFO  com.xiaog.service.impl.UserServiceImpl - users=[User [id=1, username=1001, password=123, phones=[Phone [id=1, brand=华为], Phone [id=2, brand=iphone]]]]2019-06-22 10:38:09.570 [http-bio-9999-exec-5] INFO  com.xiaog.controller.UserController - user=User [id=1, username=1001, password=123, phones=[Phone [id=1, brand=华为], Phone [id=2, brand=iphone]]]

 

 

14.注意点:我个人觉得ssh框架坑实在是多,我在搭建的过程中出现了各种各样的问题,不过最恶心的问题是spring和hibernate存在版本不兼容问题,一开始使用的是spring5+hibernate5,发现报错,就将hibernate5换成4(应该没问题了吧),结果还是报错,折腾半天,发现虽然Pom版本虽然换成4,但是之前dao层用到的HibernateDaoSupport和spring-context.xml配置中SessionFactory还是5的版本,诶,智障问题。

 

转载于:https://www.cnblogs.com/xiaogblog/p/11067988.html

你可能感兴趣的文章
用jQuery实现Ajax
查看>>
上传图片预览
查看>>
vim编辑器
查看>>
程序设计的一些原理
查看>>
iTerm的安装以及配置
查看>>
《社交网站界面设计(原书第2版)》——1.7 反模式的重要性
查看>>
2016上半年DDoS攻击报告:DDoS攻击的规模和攻击频率都在不断攀升
查看>>
nagios监控远程windows服务器
查看>>
lagp,lacp详解
查看>>
LVS之DR模式原理与实践
查看>>
导出excel
查看>>
struts2+extjs
查看>>
php安装swoole扩展支持openssl和wss遇到的坑
查看>>
Apache2.4.33安装无systemctl/service status/state显示
查看>>
全栈数据之数据挖掘的33个知识点整理
查看>>
Docker的系统资源限制及验证
查看>>
在大公司呆5年,你就废了
查看>>
mac mamp mysql no start servel
查看>>
Docker简易版:使用更少击键运行Redis,MongoDB
查看>>
laravel框架快速入门(一)
查看>>