需求:
获取不同的uuid.
StudentMapper:
public interfact StudentMapper{
String selectUuid();
}
测试类如下:
@RunWith(SpringRunner.class)
@SpringBootTest
class StudentMapperTest{
@Autowired
private StudentServcie studentService;
@Test
void selectByPrimary(){
studentService.test();
}
}
public StudentService{
void test();
}
@Service
public class StudentServiceImpl implents StudentService{
@Autowired
private StudentMapper studentMapper;
@Override
@Transactional
public void test(){
String str1 = studentMapper.selectUuid();
String str2 = studentMapper.selectUuid();
System.out.println(str1.equals(str2));
}
}
1.方法一:去掉@Transactional注解.
如下图:
@Service
public class StudentServiceImpl implents StudentService{
@Autowired
private StudentMapper studentMapper;
@Override
\\@Transactional
public void test(){
String str1 = studentMapper.selectUuid();
String str2 = studentMapper.selectUuid();
System.out.println(str1.equals(str2));
}
}
原理:每次查询会创建一个session,缺点,如果上下文有事物会导致事物无法回滚,创建session会消耗资源.
方法二,新建一个方法,并且把该方法新建一个事物如下:
@Service
public class StudentServiceImpl implents StudentService{
@Autowired
private StudentMapper studentMapper;
@Autowired
private StudentServiceImpl studentService;
@Override
@Transactional~~
public void test(){
String str1 = studentService.getUuid();
String str2 = studentService.getUuid();
System.out.println(str1.equals(str2));
}
@Transactional(progration=Propagation.REQUIRES_NEW)
public String getUuid(){
return studentMapper.selectUuid();
}
}
原理: 获取UUID需要创建session,并且不美观.
方法3,配置xml文件,如下:
<select id="selectUuid" resultType=java.lang.String" flushCache="true" statementType="STATEMENT">
select uuid()
</select>
优点:代码优雅,灵活.并且用的是上下文的session