In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces you how to carry out spring+springmvc+hibernate integration, the content is very detailed, interested friends can refer to, hope to be helpful to you.
The three frameworks have been built over and over again, although they can be built every time, but they are not efficient. Recently, I built it again, straightened out the train of thought, sorted out the areas that need to be paid attention to, and shared it.
Tools: Eclipse (jdk 1.7) spring and hibernate version 4.0 or above
It is recommended to use maven to build the project, which is much more convenient than importing the jar package manually.
1. Create a new maven web project
(those who have not used maven can learn about it first.)
Note: the maven project file structure created with Eclipse may not be correct and you need to create your own folder manually.
Correct file structure:
-src
-main
-java (class file)
-resources (profile)
-webapp (web file)
-test (test file)
-java
-resources
2.pom files, importing jar package
Importing jar packages is also a troublesome point in framework integration. Too many irrelevant packages are often imported, but they are not familiar with it and dare not delete them, so jar
There are more and more packages, and in the end, the framework is set up, but there are more than ten or twenty jar packages.
Note: the recommended practice here is that when you are not familiar with what the framework needs to import jar package, you can first import the core package, and then when you are prompted to run the project NotFoundClass, and then add relevant dependencies according to the error prompt, so that redundant jar packages will not be imported.
The recommendation can go to this site to search for the dependency you need: https://mvnrepository.com/
Pom file:
4.0.0 hcoding MyWebDemo war 0.0.1-SNAPSHOT MyWebDemo Maven Webapp http://maven.apache.org junit junit 3.8.1 test org.springframework spring-context 4.3.9.RELEASE org.springframework spring-core 4.3.9.RELEASE org.springframework spring-beans 4 .3.9.RELEASE org.springframework spring-web 4.3.9.RELEASE org.springframework spring-aspects 4.3.9.RELEASE org.springframework spring-orm 4.3.9.RELEASE org.springframework spring-webmvc 4.3.9.RELEASE Org.slf4j slf4j-api 1.7.6 aspectj aspectjrt 1.5.3 org.aspectj aspectjtools 1.8.7 javax.servlet jstl 1.2 runtime javax.annotation javax.annotation-api 1.2 Javax.servlet servlet-api 2.5 org.hibernate hibernate-core 4.2.3.Final c3p0 c3p0 0.9.1.2 mysql mysql-connector-java 5.1.35 MyWebDemo
Among them, the dependencies in the comment block import the framework core jar package, which we can import in advance, and we can change the rest according to prompts or requirements.
For example, my project uses mysql databases and c3p0 data sources, so introduce MySQL and c3p0 dependencies. If you are using other databases and data sources, you need to modify them accordingly.
The annotated part of the pom file is the dependency introduced by the missing jar package prompted by the project runtime, some of which are dependent on the spring framework, and some are dependent on servlet or jsp. If you are not familiar with it for the first time, you can not import it first, and then introduce the dependency when you report an error, so as to deepen your understanding.
3. Configuration file
This is the most important part of framework integration. The configuration files are all placed in the main/resources folder except web.xml, of course, you can also put them under other newly created folders, but the configuration file address should be modified accordingly, which will be described in more detail.
Configuration file configuration, many framework integration tutorials are not quite the same, here are my own configuration methods and practices.
Configuration files are mainly divided into four: web.xm, beans.xml, spring-mvc.xml, datasource.xml.
The configuration step is divided into two steps, the integration of spring-mvc and spring, the integration of hibernate and spring, and finally running the project. (this is also a more efficient approach, separate integration, so that even if the running project is reported wrong, it is easier to find, and branch integration is not easy to mess up.)
Next, we will start the specific configuration.
Integration of 4.spring-mvc and spring
This is the spring-mvc.xml configuration file:
This is the basic configuration of spring-mvc, mainly for request and static resource mapping.
Note:
1. It is important to note that the classes in the service layer should be excluded when scanning the package, otherwise the project runtime will report an error after integrating hibernate.
Take a look at this article for specific reasons.
two。 Then, if your package name and structure are not the same, then the scanned packet address should also be changed.
Then there is the web.xml profile:
MyWebDemo charsetEncoding org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true charsetEncoding / * spring org.springframework.web.servlet.DispatcherServlet contextConfigLocation Classpath:spring-mvc.xml 1 spring /
The spring-mvc configuration file is added to the web.xml, and the springmvc is loaded when the server starts the project. Write an example to test it after the configuration is complete.
The project structure at this time:
-src
-main
-java (class file)
-com.hcoding.controller
-com.hcoding.service
-com.hcoding.dao
-com.hcoding.model
-resources (profile)
-spring-mvc.xml
-webapp (web file)
-demo (jsp file)
-resources (static resource file: css,js,img)
-WEB-INF (web related profile)
First create a DemoController,class in the controller package:
Package com.hcoding.demo.controller;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeUnit;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.alibaba.fastjson.JSON;import com.hcoding.demo.model.People;import com.hcoding.demo.service.DemoService @ Controllerpublic class DemoController {@ RequestMapping ("/ test") public String test () {return "test";}}
Then create the demo.jsp in the demo folder:
Insert title here
This is the test page.
Start the project and enter the address in the browser: http://localhost:8080/ (project name) / test. If you succeed, you can see the page.
Integration of 5.spring and hibernate
Datasource.xml profile:
38 ${hibernate.hbm2ddl.auto} ${hibernate.dialect} ${hibernate.show_sql} ${hibernate.format_sql}
Datasource.properties file:
# database connection configjdbc.driver = com.mysql.jdbc.Driverjdbc.url = jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8jdbc.username = rootjdbc.password = 123456#hibernate confighibernate.dialect = org.hibernate.dialect.MySQLDialecthibernate.show_sql = truehibernate.format_sql = truehibernate.hbm2ddl.auto = update
Beans.xml file:
Classpath:datasource.properties 31 32 33 34
Note: it is common to import properties files into xml, and it is also a common method to write some relevant configuration data into properyties files to facilitate modification.
Another common way to import propertise is in. This method imports only one properties by default spring
When you have more than one properties file to import, you need to use another method:
Classpath:datasource.properties classpath:redis.properties
Personally, this is recommended. As the project expands, more configurations need to be imported, and there must be more than one properties file. This method is more general.
Note: the database address, user and password in the datasource.properties file are modified according to your own situation.
Modify the previous web.xml file:
MyWebDemo charsetEncoding org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true charsetEncoding / * spring org.springframework.web.servlet.DispatcherServlet contextConfigLocation Classpath:spring-mvc.xml 1 spring / contextConfigLocation classpath:beans.xml org.springframework.web.context.ContextLoaderListener
These are the four files that spring needs to configure to integrate hibernate. Loading order and inclusion relationship of the file: web.xml → bans.xml → datasource.xml → datasource.properties
Note: if your profile name and location are different, then you also need to modify it accordingly.
Note: be sure to remember to configure the transaction, otherwise the project may not report an error when operating the database, but the data in the database will not be updated (deleted or modified). You can have your own knowledge of Baidu affairs.
Write an example to test it after the configuration is complete.
Create a People.class in the model package:
Package com.hcoding.demo.model;import java.util.Set;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Transient;@Entity@Table (name= "people") public class People {@ Id @ Column (name= "ID") private int id; @ Column (name= "name") private String name; @ Column (name= "sex") private String sex Public void setName (String name) {this.name = name;} public String getSex () {return sex;} public void setSex (String sex) {this.sex = sex;}}
And create the people table in the database and add the corresponding fields.
Then create the DemoDao.class in the dao package:
Package com.hcoding.demo.dao;import javax.annotation.Resource;import org.hibernate.SessionFactory;import org.springframework.stereotype.Repository;import com.hcoding.demo.model.People;@Repository ("demoDao") public class DemoDao extends BaseSupportDao {@ Resource (name= "sessionFactory") private SessionFactory sessionFactory / * * Save object * @ param p * @ return * / public People save (People p) {return (People) sessionFactory.getCurrentSession () .save (p);}}
Create a DemoServic.class in the service package:
Package com.hcoding.demo.service;import java.util.HashSet;import java.util.Set;import javax.annotation.Resource;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.hcoding.demo.dao.DemoDao;import com.hcoding.demo.model.Book;import com.hcoding.demo.model.People;@Service ("demoService") public class DemoService {@ Resource (name= "demoDao") private DemoDao demoDao @ Transactional public void save (People p) {demoDao.save (p);} public People newPeople () {People p=new People (); p.setName ("Xiaobai"); p.setSex ("male"); return p;}}
Note: add the @ Transactional annotation to the save method to start the transaction.
Call the save method in DemoController.class to save the data:
Package com.hcoding.demo.controller;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeUnit;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.alibaba.fastjson.JSON;import com.hcoding.demo.model.People;import com.hcoding.demo.service.DemoService @ Controllerpublic class DemoController {@ Resource (name= "demoService") private DemoService demoService; @ RequestMapping ("/ test") public String test () {People p=demoService.newPeople (); demoService.save (p); return "test";}}
Start the server and access the project. Refresh the database. If the data is saved to the database, the framework is completed.
The above is the whole process of framework integration, and it is also sorted out after reading a lot of tutorials and building for many times. basically, the configuration file is relatively neat and has no extra content (because it is easy to understand the principle. I inexplicably wrote some content that I didn't have), most of the content also played an explanatory role, and I also said some things that need to be paid attention to. I made mistakes.
Of course, if you are building a framework for the first time, then there are far fewer problems, so if you encounter problems, you should be more Baidu. Of course, it will be easier to learn more about spring framework before. In addition, the project is fully annotated, so you can do it on your own if you don't know much about the notes.
On how to carry out spring+springmvc+hibernate integration to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.