MYBATIS5 Spring Integrated mybatis Things Management _java

Source: Internet
Author: User
Tags aop

Manage things by using mybatis alone

The previous MyBatis article has written related content, here continues to write a simplest demo, is a review before MyBatis content, first builds the table, establishes a simple student table:

CREATE TABLE Student
(
student_id int auto_increment,
student_name varchar () NOT NULL,
primary KEY ( student_id)
)

Establish entity class Student.java:

public class Student
{
private int studentid;
Private String studentname;
public int Getstudentid ()
{return
studentid;
}
public void Setstudentid (int studentid)
{
this.studentid = StudentID;
}
Public String getstudentname ()
{return
studentname;
}
public void Setstudentname (String studentname)
{
this.studentname = studentname;
}
Public String toString ()
{return
"Student{[studentid: + StudentID +"], [studentname: "+ Studentname +]}"; 
   }

To put it another way, it is a recommended practice to override the ToString () method on an entity class, and print each of them (or a key attribute). Then there is the Config.xml, which is the basic JDBC configuration:

<?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>
<typeAliases>
<typealias alias= "Student" type= " Org.xrq.domain.Student "/>
</typeAliases>
<environments default=" Development ">
< Environment id= "Development" >
<transactionmanager type= "JDBC"/> <datasource type=
"Pooled" >
<property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "
url" value= "JDBC: Mysql://localhost:3306/test "/> <property name=" username "value=" "root"/> <property "name=
" Password "value=" root "/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource= "Student_mapper.xml"/>
</mappers>

Then there is the student_mapper.xml, mainly the specific SQL statement:

<mapper namespace= "Studentmapper" >
<resultmap type= "Student" id= "Studentmap" >
<id column= " student_id "property=" StudentID "jdbctype=" INTEGER "/> <result column=" student_name "property="
Studentname "jdbctype=" VARCHAR "/>
</resultMap> <select id=" selectallstudents "resultmap="
Studentmap ">
select student_id, student_name from student;
</select>
<insert id= "Insertstudent" usegeneratedkeys= "true" keyproperty= "StudentID" parametertype= " Student ">
insert INTO Student (student_id, Student_name) VALUES (#{studentid, Jdbctype=integer}, #{studentname, Jdbctype=varchar});
</insert>

To create a mybatisutil.java that establishes some MyBatis basic elements, the following classes inherit this class:

public class Mybatisutil
{
protected static sqlsessionfactory SSF;
protected static reader reader;
Static
{
try
{
reader = Resources.getresourceasreader ("config.xml");
SSF = new Sqlsessionfactorybuilder (). build (reader); 
catch (IOException e)
{
e.printstacktrace ();
}
}
Protected sqlsession getsqlsession ()
{return
ssf.opensession ();
}

Enterprise-level development emphasizes:

1, definition and implementation of separate

2, layered development, usually for dao-->service-->controller, do not rule out a more than one layer/layer or less according to the specific situation

So, first write a Studentdao.java interface:

Public interface Studentdao
{public
list<student> selectallstudents ();
public int insertstudent (Student Student);
}

Finally write a Studentdaoimpl.java implementation of this interface, note to inherit the Mybatisutil.java class:

public class Studentdaoimpl extends Mybatisutil implements Studentdao
{
private static final String NAMESPACE = "S Tudentmapper. ";
Public list<student> selectallstudents ()
{
sqlsession ss = Getsqlsession ();
list<student> list = ss.selectlist (NAMESPACE + "selectallstudents");
Ss.close ();
return list;
}
public int insertstudent (Student Student)
{
sqlsession ss = Getsqlsession ();
int i = Ss.insert (NAMESPACE + "insertstudent", student);
Ss.commit ();
Ss.close ();
return i;
}
}

Write a test class:

public class Studenttest
{public
static void Main (string[] args)
{
Studentdao Studentdao = new Studentdaoimpl ();
Student Student = new Student ();
Student.setstudentname ("Jack");
Studentdao.insertstudent (student);
SYSTEM.OUT.PRINTLN ("Inserted primary key is:" + student.getstudentid ());
SYSTEM.OUT.PRINTLN ("-----Display students------");
list<student> studentlist = studentdao.selectallstudents ();
for (int i = 0, length = studentlist.size (); i < length; i++)
System.out.println (Studentlist.get (i));
}
}

The result must be empty.

I have said that this example is both as a review, and as a primer to introduce our content today, the empty reason is that the insert operation has been done, but MyBatis does not help us automatically submit things, so the display of nature is empty. At this point, you must manually commit the transaction through the Sqlsession commit () method, which is to open the comment on line 17th of the Studentdaoimpl.java class.

In addition to the basic MyBatis insert operation, this example also has the function of returning the inserted primary key ID on the insert basis.

Next, use spring to manage mybatis things, which is the most common thing management practice in enterprise development.

Using spring to manage mybatis things

On this piece, there are a lot of articles on the web, I search a lot, but either copy the sticky stickers, or not the whole case clearly, through this part, I try to explain how to use Spring management mybatis things.

Using spring to manage mybatis things, in addition to spring's necessary module beans, context, core, expression, commons-logging, you need the following:

(1) Mybatis-spring-1.x.0.jar, this is the necessary jar package for Spring integration MyBatis

(2) Database connection pool, DBCP, c3p0 can be used, I use here is Ali's Druid

(3) JDBC, TX, AOP,JDBC is basically not much to say, the use of TX and AOP is because spring's support for mybatis things is done through AOP

(4) Aopalliance.jar, this is a jar package necessary to use spring AOP

The above Jar Pack will use maven to download with Maven, no use of Maven can go to csdn, a search is available.

In the MyBatis configuration file config.xml, the part about the JDBC connection can be removed, leaving only the typealiases part:

<?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>
<typeAliases>
<typealias alias= "Student" type= " Org.xrq.domain.Student "/>
</typeAliases>

One more word, mybatis. Another configuration file student_mapper.xml do not need to be changed. Next, write the spring configuration file, my name is called Spring.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns=
"Http://www.springframework.org/schema/beans" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.2.xsd Http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/ Spring-jdbc-4.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/
Spring-aop-4.2.xsd "> <!--annotation configuration--> <tx:annotation-driven transaction-manager=" TransactionManager "/> <context:annotAtion-config/> <context:component-scan base-package= "Org.xrq"/> <!--database connection pool, where the druid of Alibaba is used--> <bean id= "DataSource" class= "Com.alibaba.druid.pool.DruidDataSource" init-method= "Init" destroy-method= "Close" > <property name= "URLs" value= "jdbc:mysql://localhost:3306/test"/> <property name= "username" value= "root" /> <property name= "password" value= "root"/> </bean> <bean id= "sqlsessionfactory" class= "Org.mybatis" . Spring. Sqlsessionfactorybean "> <property name=" configlocation "value=" Classpath:config.xml "/> <property-name=" Mapperlocations "value=" Classpath:*_mapper.xml "/> <property name=" DataSource "ref=" DataSource "/> </bean > <!--transaction manager--> <bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref="  DataSource "/> </bean> </beans>

This is mainly the transaction manager and the database connection pool two parts of the content.

In addition, we see a sqlsessionfactory, the use of mybatis friends must be familiar with this class, it is used to configure the MyBatis environment, sqlsessionfactory there are two attributes configlocation, Mapperlocations, as the name suggests, represents the location of the configuration file and the location of the mapping file, where spring automatically loads the two configuration files as long as the path is properly configured.

Then to modify the DAO's implementation class, this time no longer inherits the previous Mybatisutil this class, but inherits Mybatis-spring-1.x.0.jar the Sqlsessiondaosupport.java, the concrete code is as follows:

@Repository public
class Studentdaoimpl extends Sqlsessiondaosupport implements Studentdao
{
private Static final String NAMESPACE = "Studentmapper."
@Resource public
void Setsqlsessionfactory (sqlsessionfactory sqlsessionfactory)
{
Super.setsqlsessionfactory (sqlsessionfactory);
}
Public list<student> selectallstudents ()
{return
getsqlsession (). SelectList (NAMESPACE + " Selectallstudents ");
}
public int insertstudent (Student Student)
{return
getsqlsession (). Insert (NAMESPACE + "Insertstudent", Student);
}

Here are two annotations, respectively.

(1) @Repository, this annotation and @component, @Controller and our most common @service annotations are a function that can declare a class as a spring bean. Their difference is not in the specific semantics, more on the positioning of the annotation. As mentioned earlier, enterprise-class applications focus on the concept of tiered development, so the four similar annotations should have the following understanding:

• @Repository annotations, which correspond to the persistence layer, the DAO layer, which is directly interacting with the database, usually a method corresponding to a specific SQL statement
• @Service annotation, corresponding to the service layer, that is, services layer, its role is to combine single/multiple SQL statements, of course, if the simple words directly call a DAO layer of a method
• @Controller annotation, corresponding to the control layer that is the MVC design pattern of the control layer, its role is to receive user requests, according to the request to call different service data, and according to the requirements of the combination of data, packaging back to the front-end
• @Component annotation, this more corresponds to the concept of a component, if a bean does not know belong to take a layer, you can use @component annotation annotation

This also embodies one of the advantages of annotations: see the meaning of the note, that is, see the annotation is generally aware of the role of the class that it is located throughout the project.

(2) @Resource, this annotation and @autowired annotation is a meaning, can automatically inject attribute attribute. Since Sqlsessionfactory is the core of MyBatis, it has been declared in Spring.xml, so the bean with id "sqlsessionfactory" is injected here through the @resource annotation, Then the Getsqlsession () method can be used to obtain the sqlsession and data increase, delete, change, check.

The final thing is to write a test class test:

public class Studenttest
{public
static void Main (string[] args)
{
ApplicationContext ac = new Classpathxmlapplicationcontext ("Spring.xml");
Studentdao Studentdao = (Studentdao) ac.getbean ("Studentdaoimpl");
Student Student = new Student ();
Student.setstudentname ("Lucy");
Int J = studentdao.insertstudent (student);
System.out.println ("j =" + j + "\ n");
SYSTEM.OUT.PRINTLN ("-----Display students------");
list<student> studentlist = studentdao.selectallstudents ();
for (int i = 0, length = studentlist.size (); i < length; i++)
System.out.println (Studentlist.get (i));
}

Because the Studentdaoimpl.java class uses the @repository annotation and does not specify an alias, the Studentdaoimpl.java name in the Spring container is "first letter lowercase + remaining letter" that is "Studentdaoimpl".

Run the program, you can see the console traversing the new out of the student, that the student is directly inserted into the database, the whole process without any commit, rollback, all are by spring to help us achieve, This is the use of spring to manage things for mybatis.

Postscript

This article reviews the basic use of MyBatis and uses spring to manage things for MyBatis, gives a more detailed code example, and the friends who need it can look at the code. On the basis of this article, will also write an article, to explain the multiple data in Tanku and multiple tables between the realization of things, this demand is also belong to enterprises and applications more common needs.

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.