The simplest integration of spring+springmvc+mybatis

Source: Internet
Author: User
Tags log log string find

This baby rookie A, this project dedicated to also learning friends, the first write, write Bad don't mind. All right, just a previous writing of the small demo, very simple, but also very good understanding of the direct copy out of the changes can be run, the package needs to see itself, the rack package needs their own guide, the page to write a simple test you can run up,, caught dead!

Db.properties file: MySQL is used in the database

Dbcp.driver=com.mysql.jdbc.driver
Dbcp.validationquery=select 1

dbcp.url=jdbc:mysql://localhost:3306/here to write your database name?useunicode=true&characterencoding=utf-8& Zerodatetimebehavior=converttonull
Dbcp.username=root
Dbcp.password=root

Dbcp.init=1
Dbcp.max=5
dbcp.min=2
Dbcp.defaultautocommit=true
Dbcp.test_sql=select 1 from dual

The simplest mybatis.xml file:

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>

<!--setttings property settings--
<settings>
<!--Global Mapper enable Cache--
<setting name= "cacheenabled" value= "true"/>
< when!--query, close the associated object for immediate loading to improve performance--
<setting name= "lazyloadingenabled" value= "true"/>
<!--set the shape of the associated object load, where the field is loaded on demand (the Load field is specified by SQL) and all fields of the associated table are not loaded to improve performance--
<setting name= "aggressivelazyloading" value= "true"/>
<!--for unknown SQL queries, allowing different result sets to be returned to achieve a common effect--
<setting name= "multipleresultsetsenabled" value= "true"/>
<!--allow column labels to be used instead of column names--
<setting name= "Usecolumnlabel" value= "true"/>
<!--allows you to use a custom primary key value (such as a program-generated UUID 32-bit encoding as the key value), and the PK generation strategy for the data table will be overwritten-
<setting name= "Usegeneratedkeys" value= "true"/>
<!--given nested resultmap with field-property mapping support-
<setting name= "Automappingbehavior" value= "full"/>
<!--cache SQL for bulk update operations to improve performance--
<setting name= "Defaultexecutortype" value= "BATCH"/>
<!--the database is still not responding for more than 25,000 seconds timeout-
<setting name= "Defaultstatementtimeout" value= "25000"/>
</settings>
<!--alias--
<typeAliases>
<typealias alias= "user" type= "Here is the model bean to write" ></typeAlias>
</typeAliases>
</configuration>

Here is the simplest spring.xml file configuration

<?xml version= "1.0" encoding= "UTF-8"?
<beans xmlns= "Http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p"
Xmlns:c= "http://www.springframework.org/schema/c" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:context= "Http://www.springframework.org/schema/context" xmlns:tx= "http://www.springframework.org/schema/ Tx "
xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/ Context/spring-context.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/ Aop/spring-aop.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx.xsd ";

<!--here to write what you need to scan the control layer package, class does not write-and
<context:component-scan base-package= "Com.testing" >
<!--package Scan class, do not scan the Controller annotation class--
<context:exclude-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--introduce a resource file that is configured with a few key elements of the database connection--
<context:property-placeholder location= "Classpath:db.properties"/>

<!--database connection pool--
<bean name= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >
<property name= "Driverclassname" value= "${dbcp.driver}" ></property>
<property name= "url" value= "${dbcp.url}" ></property>
<property name= "username" value= "${dbcp.username}" ></property>
<property name= "Password" value= "${dbcp.password}" ></property>

<property name= "InitialSize" value= "${dbcp.init}" ></property>
<property name= "Maxidle" value= "${dbcp.max}" ></property>
<property name= "Minidle" value= "${dbcp.min}" ></property>
<property name= "Defaultautocommit" value= "${dbcp.defaultautocommit}" ></property>
<property name= "Validationquery" value= "${dbcp.test_sql}" ></property>
</bean>

<!--mybatis Sessionfactory--
<bean id= "Sessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" >
<!--load Data source-
<property name= "DataSource" ref= "DataSource" ></property>
<!--associated MyBatis Master profile--
<property name= "configlocation" value= "Classpath:mybatis.xml" ></property>
<!--associating mapped SQL files--
<property name= "mapperlocations" value= "Classpath:com/testing/mapper/*.xml" ></property>
</bean>

<!--mybatis Sqlsessiontemplate--
<bean id= "Session" class= "Org.mybatis.spring.SqlSessionTemplate" >
<constructor-arg ref= "Sessionfactory" ></constructor-arg>
</bean>

</beans>

Spring-mvc.xml file:

<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p"
Xmlns:c= "http://www.springframework.org/schema/c" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx"
xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ">

<!---Scan contains only controller layer--
<context:component-scan base-package= "Com.testing" >
<context:include-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller" ></ Context:include-filter>

</context:component-scan>
</beans>

The rest is the package: mainly the model Bean Layer Control Layer controller package mainly put the mapping file package also has a service package

This is the project structure:

Lib:

Inside the bean layer is not written very simple, here mainly write about the service layer services and mapper mapping files and controller layer:

Mapper Mapping File:

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace= "Com.slee" >

<select id= "Select" resulttype= "Slee" >
SELECT * FROM Sleeparams
</select>

<delete id= "Deletebyid" parametertype= "Slee" >
Delete from Sleeparams where
<if test= "Sleeparamsid!=null and Sleeparamsid! =" >
SLEEPARAMSID=#{SLEEPARAMSID}
</if>
</delete>
<update id= "Update" parametertype= "Slee" >
Update Sleeparams Set
SLEEPARAMSJX=#{SLEEPARAMSJX}
, Sleeparamspcbtype=#{sleeparamspcbtype}
, Sleeparamsems=#{sleeparamsems}
, Sleeparamscode=#{sleeparamscode}
, SLEEPARAMSBBH=#{SLEEPARAMSBBH}
, Sleeparamsmarkecode=#{sleeparamsmarkecode}
, sleeparamsstatus=#{sleeparamsstatus}
Where Sleeparamsid=#{sleeparamsid}
</update>

<insert id= "Insertslee" parametertype= "Slee"
Usegeneratedkeys= "true" keyproperty= "Sleeparamsid" >
INSERT INTO Sleeparams
(Sleeparamsid,
SLEEPARAMSJX,
Sleeparamspcbtype,
Sleeparamsems,
Sleeparamscode,
SLEEPARAMSBBH,
Sleeparamsmarkecode)
Values
(#{sleeparamsid},
#{sleeparamsjx},
#{sleeparamspcbtype},
#{sleeparamsems},
#{sleeparamscode},
#{sleeparamsbbh},
#{sleeparamsmarkecode}
)
</insert>
<select id= "Selectbyid" resulttype= "Slee" parametertype= "Slee" >
SELECT * from Sleeparams where Sleeparamsid=#{sleeparamsid}
</select>
</mapper>

Service Tier Services:

Package com.testing.service;

Import java.util.List;

Import Org.mybatis.spring.SqlSessionTemplate;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;

Import Com.testing.bean.SleeParamsBean;


@Service
public class Sleeservice {

@Autowired
Private Sqlsessiontemplate session;

Public boolean Add (Sleeparamsbean Bean) {

try {
Session.insert ("Com.slee.insertSlee", Bean);
return true;
} catch (Exception e) {

E.printstacktrace ();
}
return false;
}

Public list<sleeparamsbean> query (Sleeparamsbean Bean) {
Return Session.selectlist ("Com.slee.select", Bean);
}

public boolean Delete (Sleeparamsbean bean) {
try {
Session.delete ("Com.slee.deleteById", Bean);
return true;
} catch (Exception e) {

E.printstacktrace ();
}
return false;
}

public boolean update (Sleeparamsbean Bean) {
try {
Session.update ("Com.slee.update", Bean);
return true;
} catch (Exception e) {

E.printstacktrace ();
}
return false;
}

Public list<sleeparamsbean> Find (Sleeparamsbean Bean) {
Return Session.selectlist ("Com.slee.selectById", Bean.getsleeparamsid ());

}
}

Control Layer Controller:

Package Com.testing.controller;

Import java.util.List;

Import Javax.servlet.http.HttpServletRequest;

Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;

Import Com.testing.bean.SleeParamsBean;
Import Com.testing.service.SleeService;

@Controller
public class Sleeparamscontroller {

Private log log = Logfactory.getlog (Sleeparamscontroller.class);

@Autowired
Private Sleeservice service;

/*
* Enquiry
*/
@RequestMapping (value= "/queryslee")
Public String query (HttpServletRequest request) {
Log.info ("Enter query controller layer ==============");
Sleeparamsbean bean = new Sleeparamsbean ();
List List = Service.query (bean);
Request.setattribute ("querylist", list);
return "queryslee.jsp";

}
/*
* Add
*/
@RequestMapping (value= "Addslee", Method=requestmethod.post)
Public String Add (Sleeparamsbean bean,httpservletrequest request) {
Log.info ("Enter the added controller layer");
Boolean flag = Service.add (bean);
if (flag) {
Request.setattribute ("Message", "Add success!");
}else {
Request.setattribute ("Message", "Add failed!") ");
}
return "addslee.jsp";
}
/*
* Query Individual
*/
@RequestMapping (value= "Findslee")
Public String Find (httpservletrequest Request,sleeparamsbean Bean) {
Log.info ("Enter query single data controller layer");

Sleeparamsbean bean2 = Service.find (Bean). Get (0);
Request.setattribute ("Slee", bean2);
return "updateslee.jsp";
}
@RequestMapping (value= "Updateslee", Method=requestmethod.post)
Public String Update (Sleeparamsbean bean, httpservletrequest request) {
Log.info ("Access to Modified controller layer");

Boolean flag = Service.update (bean);

if (flag) {
Request.setattribute ("message", "modified successfully");
}else {
Request.setattribute ("message", "modification Failed");
}
return "queryslee.jsp";
}
/*
* Delete
*/
@RequestMapping (value= "Deleteslee")
Public String Delete (httpservletrequest Request,sleeparamsbean bean) {
Log.info ("Go to deleted Pages");
Boolean flag = Service.delete (bean);
if (flag) {
Request.setattribute ("message", "delete succeeded");
}else{
Request.setattribute ("message", "Delete failed");
}
return "queryslee.jsp";
}
}

The simplest integration of spring+springmvc+mybatis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.