spring cloud build (transaction)

Today we talk about how to start a business.

Before, we configured transaction start in JpaConfiguration.

See: https://blog.csdn.net/hanjun0612/article/details/105239557

 

If the transaction is not started, an error will be reported: Executing an update / delete query

 

One, Dao affairs

There is this paragraph, which represents the start of Dao affairs.

@EnableTransactionManagement (mode = AdviceMode.ASPECTJ)
So, if it ’s Dao ’s method,

We just need to add: @Transactional and @Modifying

@Repository
public interface AccountDao extends JpaRepository<Account,Integer> {
    @Transactional
    @Modifying
    @Query(value="update test_account set balance=balance-:balance where name=:name",nativeQuery=true)
    void update(@Param(value = "name")String name,@Param(value = "balance")Double balance);
}

 

Second, Service transaction

If you are a Service transaction, you need to add @EnableTransactionManagement in the Application startup

@SpringBootApplication(scanBasePackages = {"com.test"})
@EnableEurekaClient
@EnableTransactionManagement
public class Service1Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Service1Application.class, args);
    }
 
}

 

Service call

package com.test.service;
 
import com.test.dao.AccountDao;
import com.test.model.Account;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.Transient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @author Tyler
 * @date 2020/3/31
 */
 
@Service("accountService")
public class AccountServiceImpl implements AccountService{
 
    @PersistenceContext
    EntityManager em;
 
    @Transactional
    public void Update(Account entity) throws Exception {
        String sql = "update test_account set balance=balance+:balance where name=:name";
 
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("balance",entity.getBalance());
        params.put("name",entity.getName());
 
        Query query = em.createNativeQuery(sql);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
                query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        query.executeUpdate();
        //throw new Exception("hello");
    }
 
}

 

It depends on you, where you control the transaction, wherever you start.

Guess you like

Origin www.cnblogs.com/hanjun0612/p/12692923.html