Today let's continue with Spring's discussion. Let's not talk too much. Goods will be finished!!!
Integration of Spring and MyBatis (IDEA)
I. Integration process
1. IDEA builds a maven project for webapp, copies the pom.xml file, and modifies the project name.
Create java and resources in the main directory
2. Modification of configuration file (db.properties)
3. Create a config directory, import configuration classes for MyBatis and spring, and create package packages
4. Define Pojo classes
User class:
@Table(name="user")
public class User implements Serializable{
@Id
private String uid;
private String username;
private String password;//get set Reference or no reference toString
}
5. Define the Dao interface, inherit the generic Mapper, set the Mapper mapping & register the Dao
6. Define Service
UserServiceImpl class:
/**
* Transactional Note: Mark transactions for current service managed by spring
* No exception occurred, spring commits the transaction
* An exception was thrown, spring rolled back the transaction
*/
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
}
7. Define Test
UserTest class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class, MyBatisConfiguration.class})
public class UserTest {
@Resource
private UserService userService;
@Test
public void run1(){
System.out.println(userService);
}
}
2. Practice using:
Case 1: Paging query
Test class:
/**
* Paging Query
*/
@Test
public void run3(){
PageInfo<User> pi = userService.selectUlistForPage(1);
for (User user : pi.getList()) {
System.err.println(user);
}
}
Service layer:
/**
* Paging Query
* @param i
* @return
*/
@Override
public PageInfo<User> selectUlistForPage(int i) {
//1. Use Paging Assistant to Open Paging
PageHelper.startPage(i,2);
//2. Query
List<User> ulist = userDao.selectAll();
//3. Encapsulate data and return
return new PageInfo<User>(ulist);
}
Case 2: Conditional Query
Test class:
/**
* Conditional Query
*/
@Test
public void run4(){
List<User> ulist = userService.selectUlistByParam("123");
for (User user : ulist) {
System.out.println(user);
}
}
Service:
/**
* Conditional Query
* @param s
* @return
*/
@Override
public List<User> selectUlistByParam(String s) {
//1. Splicing Conditions
Example example = new Example(User.class);
Example.Criteria c = example.createCriteria();
c.andLike("password","%"+s+"%");
//2. Query
List<User> ulist = userDao.selectByExample(example);
//3. Return Results
return ulist;
}
Summary:
MyBatis integrated with spring.MyBatis handed the following actions to spring management
- Get Dao
- Close Session
- Commit and rollback of transactions (transaction control)
Congratulations, you know a little more!!!
The more you know, the more you don't know!
~Thank you for reading like-minded, your support is my greatest motivation to learn! Go on, strangers work together, reluctantly!!