简体   繁体   中英

Spring Boot and transaction boundary

I'm using Spring boot for rest back end system with spring data , I have three main layers (controller,service , dao).

I annotated the service class with @Transactional and within one of it's methods i'm retrieving some entity having @ManyToMany relationship with other Entity .

I want only to get the main entity and i'm depending on the lazy of the @ManyToMany.

The problem is after returning back from the service to the controller when I hit on the (many) side a sql statement is issues and retrieved the collection as if the transaction is still running !!

@SpringBootApplication
@ComponentScan(value = { "net.pd.ethraa" })
@EnableJpaRepositories(basePackages = { "net.pd.ethraa.dao" })
@EntityScan(basePackages = "net.pd.ethraa.common.model")
@EnableTransactionManagement
public class EthraaApplication extends SpringBootServletInitializer {
}

 @RequestMapping(path = "/get/{id}", method = RequestMethod.GET)
    public Account getAccount(@PathVariable("id") Long id) {
    Account account = accountService.find(id);

    for (Permission p : account.getPermissions()) {
        System.out.println(p.getName());
    }
    return account;

    }


@Service
@Transactional
public class AccountServiceImpl implements AccountService {

 @Override
    public Account find(Long id) {
    return accountDao.findOne(id);

    }
}

@Repository
public interface AccountDao extends CrudRepository<Account, Long> {}


@Entity
@Table(name = "ACCOUNT", uniqueConstraints = @UniqueConstraint(columnNames = { "mobile", "email" }))
public class Account extends BaseEntity {
 @ManyToMany
    @JoinTable(name = "ACCOUNT_PERMISSION")
    private List<Permission> permissions;
}

My expectation is when I hit the collection outside the service it should be outside the transaction boundary and gives lazy exception but it doesn't ?

Spring Boot enables OpenEntityManagerInViewInterceptor by default which allows for this behavior.

You can disable it using following property in your application config file:

spring.jpa.open-in-view=false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM