SPRINGMVC Project Complete Example 04 integration with MyBatis

Source: Internet
Author: User

Baidu Encyclopedia:

MyBatis is an open source project for Apache Ibatis, which was migrated to Google code by the Apache Software Foundation in 2010 and renamed MyBatis. Migrated to GitHub in November 2013.

The term ibatis is derived from the combination of "Internet" and "Abatis" and is a Java-based persistence layer framework. Ibatis provides a durable layer framework that includes SQL maps and Data Access Objects (DAO)

Source: Http://baike.baidu.com/link?url=Z0he9EpOBOMlHLH_MpCWQ3Shojuzg0ixWNe6ILPwyMng98oskR_Cr9Nb5G3A3sqAJ4Y98XlUTNUuJ7y0V6e7Xa

The front used is jdbctemplate, not convenient, now we put him and mybatis integration

The jar required

One to seamlessly connect with spring, one is the core package of MyBatis

First you need to add a configuration file

<!--mybatis file--

<bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" >

<property name= "DataSource" ref= "DataSource"/>

<!--automatically scan map files--

<property name= "Mapperlocations" >

<array>

<value>classpath:mapper/*.xml</value>

</array>

</property>

</bean>

<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" >

<property name= "Basepackage" value= "Com.bbs.dao.mapper"/>

<property name= "Sqlsessionfactorybeanname" value= "Sqlsessionfactory"/>

</bean>

This paragraph is a fixed format of Ha, DataSource is our data source is also connected to the database, previously set over the

Using MyBatis generally we need two files, one is the mapper mapping interface, one is the XML, which writes the SQL

It's plain to mybaits that SQL in XML, after processing, can be called through an interface in mapper

Note that the interface name is the ID in the XML

So when it comes to this, it's clear that the XML for the automatic scan map file above is where we write SQL.

The following is the mapper interface corresponding to the package, it is written in the Mapper interface

So if you want to use it, copy it and change the two positions.

And, you know, in contrast to eclipse, when you create a project, SRC is the classpath.

Please study mybaits carefully.

Configuration files can be configured individually, or you can directly write Applicationcontext,xml, and now we are writing together

And then just create a new file inside the project.

Create a new package, com.bbs.dao.mapper two new interfaces inside

SRC below create a new folder, Mapper, inside a new two configuration file

As shown

After the configuration file is set up, the files are created as well.

is to write SQL and interfaces.

SQL is naturally written according to the rules of others.

Usermapper.xml

<?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.bbs.dao.mapper.UserMapper">

 

<select id="getMatchCount" parameterType="com.bbs.domain.User"

resultType="java.lang.Integer">

SELECT count(*)

FROM

t_user

WHERE

user_name=#{userName}

and password=#{password}

</select>

 

<select id="findUserByUserName" parameterType="com.bbs.domain.User"

resultType="com.bbs.domain.User">

SELECT

t_user.user_id as userId,

t_user.user_name as userName,

t_user.credits as credits,

t_user.password as password,

t_user.last_ip as lastIp,

t_user.last_visit as lastVisit

 

 

FROM

t_user

WHERE

user_name=#{userName}

</select>

 

 

<update id="updateLoginInfo" parameterType="com.bbs.domain.User">

 

UPDATE t_user

<set>

<if test="lastVisit !=null">

last_visit = #{lastVisit},

</if>

<if test="lastIp !=null and lastIp !=‘‘">

last_ip = #{lastIp},

</if>

<if test="credits !=null and credits !=‘‘">

credits = #{credits},

</if>

 

</set>

where user_id=#{userId}

</update>

 

<insert id="insertUser" parameterType="com.bbs.domain.User">

insert into t_user(

user_name,

credits,

password,

last_ip,

last_visit

)

values(

#{userName},

#{credits},

#{password},

#{lastIp},

#{lastVisit}

 

)

</insert>

 

 

 

<update id="updateUserInfo" parameterType="com.bbs.domain.User">

 

UPDATE t_user

 

<set>

<if test="lastVisit !=null">

last_visit = #{lastVisit},

</if>

<if test="lastIp !=null and lastIp !=‘‘">

last_ip = #{lastIp},

</if>

<if test="credits !=null and credits !=‘‘">

credits = #{credits},

</if>

 

</set>

where user_id=#{userId}

</update>

 

 

</mapper>

Loginlogmapper.xml

<?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.bbs.dao.mapper.LoginLogMapper">

 

<insert id="insertLoginLog" parameterType="com.bbs.domain.LoginLog">

insert into t_login_log(

user_id,

ip,

login_datetime

)

values(

#{userId},

#{ip},

#{loginDate}

)

</insert>

</mapper>

Speaking of which, say a few common questions.

1, the name of the field in the database and the name in the Java code, you should note that if you do not remember the Select when you want as a bit of code, or how people know how to map

2,insert,update, the front is the database, followed by the Java code

3. Be careful when judging the entry conditions using if


For example, the lastvisit here is a datetime format in the database, the Java code is the date (util) type, when using if the lastvisit can not be with the following lastip like to have a what and lastip!= ", Because it is a time object, compared to the time as a string, if you use it will be an error,

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:

### Error updating database. Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String

..........

It's just SQL, and the notes are not written, after all, it's a simple example.

Then the interface with the XML map

Usermapper.java

package com.bbs.dao.mapper;

 

import com.bbs.domain.User;

 

 

public interface UserMapper {

public Integer getMatchCount(User user);

 

public User findUserByUserName(User user);

 

public void updateLoginInfo(User user);

public void insertUser(User user);

public void updateUserInfo(User user);

}

Loginlogmapper.java

package com.bbs.dao.mapper;

 

import com.bbs.domain.LoginLog;

 

public interface LoginLogMapper {

 

public void insertLoginLog(LoginLog loginLog);

}

This way, you can execute SQL through the Mapper interface.

Before the time our interface is not very standardized, we now regulate

To split the original Userservice.java.

Disassembled into

Userservice.java

Loginlogservice.java

These two interfaces

When actually used, use their implementation class

interface-oriented programming well, the benefits of self-Baidu

Userservice.java

package com.bbs.service;

 

import com.bbs.domain.User;

 

public interface UserService {

 

public Boolean hasMatchUser(User user);

public User findUserByUserName(User user);

public void loginSucess(User user);

public void insertUser(User user);

 

 

public void UpdateUser(User user);

 

}

Userserviceimpl.java

package com.bbs.service;

 

import java.util.Date;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.bbs.dao.mapper.UserMapper;

import com.bbs.domain.LoginLog;

import com.bbs.domain.User;

 

@Service

public class UserServiceImpl implements UserService {

 

@Autowired

private UserMapper userMapper;

@Autowired

private LoginLogService loginLogService;

@Override

public Boolean hasMatchUser(User user) {

Integer matchCount = userMapper.getMatchCount(user);

if(matchCount > 0){

return true;

}else{

return false;

}

 

 

}

 

@Override

public User findUserByUserName(User user) {

return userMapper.findUserByUserName(user);

}

 

@Override

public void loginSucess(User user) {

 

user.setCredits(5+user.getCredits());

user.setLastVisit(new Date());

LoginLog loginLog = new LoginLog();

loginLog.setUserId(user.getUserId());

loginLog.setIp(user.getLastIp());

loginLog.setLoginDate(new Date());

userMapper.updateLoginInfo(user);

loginLogService.insertLoginLog(loginLog);

}

 

@Override

public void insertUser(User user) {

userMapper.insertUser(user);

}

@Override

public void UpdateUser(User user) {

userMapper.updateUserInfo(user);

}

 

}

Loginlogservice.java

package com.bbs.service;

 

import com.bbs.domain.LoginLog;

 

public interface LoginLogService {

 

public void insertLoginLog(LoginLog loginLog);

}

Loginlogserviceimpl.java

package com.bbs.service;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.bbs.dao.mapper.LoginLogMapper;

import com.bbs.domain.LoginLog;

 

@Service

public class LoginLogServiceImpl implements LoginLogService {

 

@Autowired

private LoginLogMapper loginLogMapper;

@Override

public void insertLoginLog(LoginLog loginLog) {

loginLogMapper.insertLoginLog(loginLog);

}

 

}

This interface and his implementation classes are all written.

Be aware that @service and @autowired ha

So until now, the logic of the project is like this.

Spring+mybaits

The configuration file is configured with information such as the database, configure some of the packages that need to be scanned automatically, to scan the annotations in the package, it is important to integrate the MyBatis

Using MyBatis to manipulate the database, mapper to call directly

Transformed into an interface-oriented programming

Call through UserService and Loginlogservice, actually implement the class.

The implementation class operates the database by combining calls to the interfaces provided by mapper to manipulate the data

The transformation of the project was completed

The test also has to be modified.

package test.bbs.service;

 

import static org.junit.Assert.*;

 

import java.util.Date;

 

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 com.bbs.domain.User;

import com.bbs.service.UserService;

 

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"/applicationContext.xml"})

 

public class TestUserService {

 

@Autowired

private UserService userService;

@Test

public void hasMAtchUser(){

User user1 = new User();

User user2 = new User();

user1.setUserName("admin");

user1.setPassword("123456");

user2.setUserName("admin");

user2.setPassword("11111");

boolean b1 = userService.hasMatchUser(user1);

//boolean b2 = userService.hasMatchUser(user2);

assertTrue(b1);

//assertTrue(b2);

}

@Test

public void findUserByUserName(){

User user = new User();

user.setUserName("admin");

 

User user1 = userService.findUserByUserName(user);

System.out.println(user1.getUserName());

assertEquals(user1.getUserName(),"admin");

}

 

@Test

public void loginSucess(){

User user = new User();

user.setUserName("admin");

user= userService.findUserByUserName(user);

userService.loginSucess(user);

}

@Test

public void insertUser(){

User user = new User();

user.setUserName("user1");

user.setPassword("123456");

user.setCredits(0);

user.setLastIp("255.255.255.255");

user.setLastVisit(new Date(0) );

userService.insertUser(user);

 

}

@Test

public void updateUserInfo(){

User user = new User();

user.setUserId(2);

user.setLastVisit(new Date() );

user.setCredits(5+user.getCredits());

 

userService.UpdateUser(user);

 

}

}

The visual is all done, huh?

The above is a basic project of Spring+mybatis (backstage)

SPRINGMVC Project Complete Example 04 integration with 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.