<!-- 引入属性文件 -->
<context:property-placeholder location="db.properties"/>
<!-- 创建数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 通过数据源配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.The JdbcTemplate "> <-! Configuration transaction manager, whether it is configured with the transaction annotation mode or xml way, there must be DataSourceTransactionManager transaction management device support -> </ bean>
<Property name =" dataSource "ref =" dataSource "> </ Property>
<bean the above mentioned id = "DataSourceTransactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<Property name = "dataSource" ref = "dataSource"> </ Property>
</ bean>
<-! Configuration service announcements - ->
<tx: advice the above mentioned id = "tx" transaction-Manager = "DataSourceTransactionManager">
<tx: the Attributes>
<- transaction set again in setting a good starting point expression under ->!
<tx: Method, name = "buyBook" />
<tx: method, name = "checkOut" />
<- only select the method will only be the beginning of a transaction ->!
<tx: method, name = "select *" = the Read-only "to true" />
<TX: Method name = "INSERT *" />
<TX: Method name = "Update *" />
<tx:method name="delete*"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置切入点表达式 -->
<AOP: config>
<AOP: "(. * * * com.atguigu.book_xml.service.impl (..).) Execution" = the pointcut expression The ID = "PointCut" />
<AOP: the advice-REF = Advisor " TX "the pointcut-REF =" PointCut "/>
</ AOP: config>
</ Beans>
in xml which defines a data source bean, data source bean again transaction manager bean lock dependency, a data source connection objects this time with connection is the same, spring default management object singleton
Package com.atguigu.book.controller;
Import of java.util.ArrayList;
Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;
Import ORG .springframework.stereotype.Controller;
Import com.atguigu.book.service.BookService;
Import com.atguigu.book.service.Cashier;
@Controller
public class BookController {
@Autowired
private BookService service;
@Autowired
private Cashier cashier;
public void buyBook() {
service.buyBook("1", "1001");
}
public void checkOut() {
List<String> bids = new ArrayList<>();
bids.add("1");
bids.add("2");
cashier.checkOut("1001", bids);
}
}
package com.atguigu.book.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.atguigu.book.service.BookService;
import com.atguigu.book.service.Cashier;
@Service
@Transactional
public class CashierServiceImpl implements Cashier {
@Autowired
private BookService service;
@Override
public void checkOut(String uid, List<String> bids) {
for (String bid : bids) {
service.buyBook(bid, uid);
}
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.5iyouxue.com /schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context /schema/context/spring-context-4.0.xsd http://www.oushengyuL.cn
http://www.springframework.org/schema/aop http://www.changjianyL.cn / Schema / AOP / Spring - 4.0.xsd-AOP
http://www.springframework.org/schema/tx http://www.huangzuyuL.cn Schema / TX / TX-4.0.xsd-Spring ">
<context: Component Base-Package-Scan = "com.atguigu.book_xml"> </ context: Component-Scan>
the System class contains the fields and methods, he can not be instantiated
// for garbage collection
public static void GC ()
// terminate running java virtual machine. Parameter is used as a status code, by convention, indicates abnormal termination of the non-0
public static void Exit (int Status)
//System.out.println (System.currentTimeMillis ());
// Returns the number from January 1, 1970 to the present time in milliseconds (Coordinated Universal Time)
public static currentTimeMills (www.chengsyl.cn)
public static void arraycopy (Object src, int srcPos, Object dest, int destPos, int length)
// src - the source array.
// srcPos - starting position of the source array.
// dest - the destination array.
// destPos - starting position of the destination data.
// length - the number of array elements to be copied.
The method of use cases arraycopy
int [] = {ARR. 11, 22 is, 33 is, 44 is, 55};
int [] = {arr2 is. 6,. 7,. 8,,. 9, 10};
System.arraycopy (ARR,. 1, arr2 is, 2, 2);
System.out.println (of Arrays.toString (ARR));
System.out.println (of Arrays.toString (arr2 is));
// run results
[11, 22, 33, 44, 55]
[6 ,. 7, 22 is, 33 is, 10]
currentTimeMills () use cases
package cn.bwh_www.jinLiyLd.cn2_currenTimeMillis;
{class SystemDemo public
public static void main (String [] args) {
// this statistical program run time
Long Start = System.currentTimeMillis ();
for (int X = 0; X www.chaoylgw.cn/ <10000; X ++ ) {
System.out.println ( "the Hello" + X);
}
Long End = System.currentTimeMillis ();
System.out.println ( "total time" + (end - start) + " msec");
}
}
// operating results
Hello9997
Hello9998
Hello9999
took a total of 79 milliseconds
System.gc () can be used for garbage collection. before the memory occupied by an object using the System.gc () recycling program to clean up the resources required by calling the appropriate method, in the absence of clearly specified resource cleanup, Java enhance the default mechanism to clean up the object's resources, it is to call finalize object class () method, the role finalize () method will be JVM release memory space an object occupies call. the subclasses override this method, you can clean up resources occupied by the object, the method does not call chain, it must be implemented manually.
From the results of the proceedings can be found in the implementation of system.gc () before the system will automatically call the finalize () method clears the resource object possession. By super.finalize () can be achieved from the method call to the next, which is to release its own resources, and then release the resources of the parent class.
But do not call the garbage collection frequently in the program, because every time the garbage collection jvm will be forced to start the garbage collector runs, it will consume more system resources to run a Java program with the normal competition for resources, only in the implementation of a large number of release the object before the garbage collector calls the best.
com.atguigu.book.service.impl Package;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.stereotype.Service;
Import org.springframework.transaction.annotation.Isolation;
Import org.springframework.transaction .annotation.Propagation;
Import org.springframework.transaction.annotation.Transactional;
Import com.atguigu.book.dao.BookDao;
Import com.atguigu.book.exception.MyException;
Import com.atguigu.book.service.BookService;
@ Service
The Transactional @ //
public class BookServiceImpl the implements the BookService {
@Autowired
Private BookDao DAO;
/ **
* @Transactional: all the method operations as a transaction management
* used in the method, only the effect of a method of
* use the classes , all methods of the class have the effect of
properties that can be set * @Transactional:
*
* propagation: method a and method B are the transaction, B when the call, the transaction will be propagated to the B method a in a, B method for handling matters is the spread of behavior Affairs
* Propagation.REQUIRED: You must use the caller's transaction
* Propagation.REQUIRES_NEW: the caller's transaction suspension, does not use caller's transaction, using the new transaction processing
*
* isolation: transaction isolation level, in the case of concurrent a predetermined operation data
* read uncommitted: dirty read 1
* read Committed: non-repeatable read 2
* repeatable read: magic reading 4
* serialization: low performance, consumption 8
*
*
* timeout: maximum execution (wait) until the transaction force a rollback of time
*
* ReadOnly: Specifies the current series of operations in the transaction is read-only
* If set to read-only, with or without write operations in a transaction, mysql will request access to the data at the time, not locked, improve performance
* But if there the write operation, a read-only proposal must not be set
*
* rollbackFor | rollbackForClassName | noRollbackFor | noRollbackForClassName: set transaction rollback conditions
* /
the @Transactional (propagation = Propagation.REQUIRES_NEW, timeout = 3, noRollbackFor = {NullPointerException.class, } MyException.class)
public void buyBook (Bid String, String UID) {
/ * the try {
the Thread.sleep (5000);
} the catch (InterruptedException E) {
// the TODO Auto-Generated Block the catch
e.printStackTrace (www.feishenbo. CN);
} * /
Integer = dao.selectPrice. price (Bid);
dao.updateSt (Bid);
dao.updateBalance (UID,. price);
}
}
package com.atguigu.book.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.atguigu.book.dao.BookDao;
import com.atguigu.book.exception.MyException;
@Repository
public class BookDaoImpl implements BookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer selectPrice(String bid) {
Integer price = jdbcTemplate.queryForObject("select price from book where bid = ?", new Object[] {bid}, Integer.class);
return price;
}
@Override
public void updateSt(String bid) {
//获取该书籍的库存
Integer st = jdbcTemplate.queryForObject("select st from stock where sid = ?", new Object[] {bid}, Integer.class);
if(st <= 0) {
throw new RuntimeException();
}else {
jdbcTemplate.update("update stock set st = st -1 where sid = ?", bid);
}
}
@Override
public void updateBalance(String uid, Integer price) {
Integer balance = jdbcTemplate.queryForObject("select balance from money where uid = ?", new Object[] {uid}, Integer.class);
if(balance < price) {
throw new MyException("余额不足");
}else {
jdbcTemplate.update("update money set balance = balance - ? where uid = ?", price, uid);
Why add a comment @Transtaional can ensure consistency and transactional integrity?
Guess you like
Origin www.cnblogs.com/qwangxiao/p/11030133.html
Recommended
Ranking