Spring Annotations Learning Letters (5) business tier transaction processing
Key issues in the business layer is the transaction control! Spring annotation-type transaction processing is actually very simple!
Related reference:
Spring Annotations Learning Letters (1) to build a simple Web application
Spring Annotations Learning Letters (b) the control layer comb
Spring Annotations Learning Letters (3) form page handling
Spring Annotations Learning Letters (d) Analysis of persistence layer
Spring Annotations Learning Letters (5) business tier transaction processing
Here will be used the following package:
Quote
aopalliance-1.0.jar
commons-collections.jar
commons-dbcp.jar
commons-logging-1.1.1.jar
commons-pool.jar
jstl.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.6-bin.jar
spring-aop-2.5.6.jar
spring-beans-2.5.6.jar
spring-context-2.5.6.jar
spring-context-support-2.5.6.jar
spring-core-2.5.6.jar
spring-jdbc-2.5.6.jar
spring-tx-2.5.6.jar
spring-web-2.5.6.jar
spring-webmvc-2.5.6.jar
standard.jar
Major increase in spring-aop-2.5.6.jar's AOP support package!
Before we AccountService added @ Transactional annotation label, but to want to really play a role in affairs, but also require some configuration.
Main dao.xml files need to be adjusted
dao.xml-transaction management
<bean
p:dataSource-ref="dataSource" />
<tx:annotation-driven
transaction-manager="transactionManager" />
Refine what AccountService interface method
AccountService.java
/**
* 2010-1-23
*/
package org.zlex.spring.service;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import org.zlex.spring.domain.Account;
/**
* Account service interface
*
* @author <a href="mailto:zlex.dongliang@gmail.com"> Mr Tung </a>
* @version 1.0
* @since 1.0
*/
public interface AccountService {
/**
* Get an account
*
* @param username
* @param password
* @return
*/
@Transactional(readOnly = true)
Account read(String username, String password);
/**
* Get an account
*
* @param id
* @return
*/
@Transactional(readOnly = true)
Account read(int id);
/**
* Registered users
*
* @param account
* @return
*/
@Transactional(readOnly = false, rollbackFor = DataAccessException.class)
Account register(Account account);
}
Here I put annotation @ Transactional adjusted to a specific method, that is written like this, then add comments in any way belong to the transaction marked configuration!
Account register (Account account); used as the role of the user registration!
@ Transactional (readOnly = true) read-only attribute
@ Transactional (readOnly = false, rollbackFor = DataAccessException.class) read-off, face DataAccessException exception rollback!
If your Eclipse integrated SpringIDE, you can look at this time of the xml configuration files and AccoutServiceImpl.java change!
This time, to a user registration feature presentation, intentionally create an exception in a position to see whether it is normal rollback!
Look at the registration controller
RegisterController.java
/**
* 2010-2-4
*/
package org.zlex.spring.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.zlex.spring.domain.Account;
import org.zlex.spring.service.AccountService;
/**
* User registration controller
*
* @author <a href="mailto:zlex.dongliang@gmail.com"> Mr Tung </a>
* @version 1.0
* @since 1.0
*/
@Controller
@RequestMapping(value = "/register.do")
public class RegisterController {
@Autowired
private AccountService accountService;
@InitBinder
public void initBinder(WebDataBinder binder) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, "birthday",
new CustomDateEditor(format, true));
}
@RequestMapping(method = RequestMethod.GET)
public String initForm(ModelMap model) {
Account account = new Account();
model.addAttribute("account", account);
// Jump directly to the login page
return "account/register";
}
@RequestMapping(method = RequestMethod.POST)
protected String submit(@ModelAttribute("account") Account account) {
int id = accountService.register(account).getId();
// Jump to user information page
return "redirect:profile.do?id=" + id;
}
}
@ InitBinder used to form custom attribute binding. Here we are asked to enter a date format's birthday.
@ RequestMapping (method = RequestMethod.GET) is used to initialize the page.
@ RequestMapping (method = RequestMethod.POST) used to submit the page.
Look at the registration page
register.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Registration </title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/calendar.js"></script>
</head>
<body>
<fieldset><legend> User registration </legend><form:form
commandName="account">
<ul>
<li><form:label path="username"> User name :</form:label><form:input
path="username" /></li>
<li><form:label path="password"> Password :</form:label><form:password
path="password" /></li>
<li><form:label path="birthday"> Birthday :</form:label><form:input
path="birthday" /></li>
<li><form:label path="email">Email:</form:label><form:input
path="email" /></li>
<li>
<button type="submit"> Registration </button>
<button type="reset"> Reset </button>
</li>
</ul>
</form:form></fieldset>
</body>
</html>
Here I used a JavaScript Date Control Tags:
<script type="text/javascript" src="js/calendar.js"></script>
Use them like this:
Very easy to use! ! ! Of course, you can use the JE on the JS that controls!
Next to tweak the AccountService interface and its implementation AccountServiceImpl
AccountService.java
public interface AccountService {
// Omit
/**
* Registered users
*
* @param account
* @return
*/
@Transactional(readOnly = false, rollbackFor = DataAccessException.class)
Account register(Account account);
// Omit
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
// Omit
@Override
public Account register(Account account) {
accountDao.create(account);
return accountDao.read(account.getUsername());
}
}
In order to insert a record to obtain the current user's primary key, we have to do this job! Ray was a little man ~
From the structure considered, it is in line with operational requirements to achieve! If you use iBatis or Hibernate, the problem there is an IO handle complete database!
Let us now look AccountDao interface and its implementation AccountDaoImpl
AccountDao.java
public interface AccountDao {
// Omit
/**
* Building the user records
*
* @param account
* @return
*/
void create(Account account);
}
AccountDaoImpl.java
@Repository
public class AccountDaoImpl implements AccountDao {
// Omit
@Override
public void create(Account account) {
String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";
jdbcTemplate.update(sql, new Object[] { account.getUsername(),
account.getPassword(), account.getBirthday(),
account.getEmail() });
}
}
Come to a sign-up demo!
Registration:
Information Display:
To make an accident!
Take a look at the database the current situation!
In the past month AccountDaoImpl destruction!
@Override
public void create(Account account) {
String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";
jdbcTemplate.update(sql, new Object[] { account.getUsername(),
account.getPassword(), account.getBirthday(),
account.getEmail() });
[color=red]throw new RecoverableDataAccessException("TEST");[/color]
}
We try to post in the implementation of End Insert statement throws DataAccessException exception (RecoverableDataAccessException)!
Registered to try!
Click Submit to see the return of an exception!
Exception rollback force!
Database, of course, what is not, I do not nonsense!
Related to achieve Annex!
Related reference:
Spring Annotations Learning Letters (1) to build a simple Web application
Spring Annotations Learning Letters (b) the control layer comb
Spring Annotations Learning Letters (3) form page handling
Spring Annotations Learning Letters (d) Analysis of persistence layer
Spring Annotations Learning Letters (5) business tier transaction processing
Related Posts of Spring Annotations Learning Letters (5) business tier transaction processing
-
hibernate generic generic DAO
hibernate generic generic DAO
-
Servlet brief introduction
Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...
-
First Hibernate Example
Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and oth ...
-
spring struts2.0 hibernate environmental structures .. despair carried out more than one hour only with good.
http://www.qqread.com/java/2008/06/f413762.html Look here. . Note added myeclipse support spring when necessary add the commons-dbcp database connection pool package. And to add hibernate support. . Finally add struts2 support. . Oh the lazy point. . ...
-
Spring2.0 + hibernate3.1 + log4j + mysql demo
applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com
-
Hibernate secondary cache
Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...













Leave a Reply