Referring to the source code, many students fear, in fact, this is very normal from the point of view of human nature, because people of the unknown things, are very afraid, secondly, your heart may always feel, as if not principle can still work ah, there is no strong desire in your subconscious. From the experience of reading source code,Java three framework SSM,Mybatis source is the most suitable for entry.
Simple to use
This is a simple example of Mybatis saving objects
@Test
public void testSave(a) throws Exception {
// Create a sessionFactory object
SqlSessionFactory sf = new SqlSessionFactoryBuilder().
build(Resources.getResourceAsStream("mybatis-config.xml"));
// Get the session object
SqlSession session = sf.openSession();
// Create entity objects
User user = new User();
user.setUsername("toby");
user.setPassword("123");
user.setAge(23);
// Save data to database
session.insert("com.toby.mybatis.domain.UserMapper.add", user);
// Commit transaction, this is a must, otherwise even if the SQL is not saved in the database
session.commit();
// Close the resource
session.close();
}
Copy the code
<mapper namespace="com.toby.mybatis.domain.UserMapper">
<! --#{} find the corresponding attribute value in the object passed in -->
<! ParameterType What type of argument is passed in -->
<insert id="add" parameterType="com.toby.mybatis.domain.User">
INSERT INTO USER (username,password,age) VALUES (#{username},#{password},#{age})
</insert>
</mapper>
Copy the code
Which leads to the theme
But in reality, we don’t do that, we do CRUD operations through Mapper interfaces, calling interface methods, so the key is, what does this interface do, that’s what we care about.
Just look at what’s going on in this code and see what the Mapper interface is doing.
public void testGetObject(a) throws Exception {
SqlSession session = MybatisUtil.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.get(5L);
System.out.println(user);
session.close();
}
Copy the code
public interface UserMapper {
public void add(User user);
public User get(Long id);
}
Copy the code
The flow chart
But I think a flow chart and a sequence diagram will tell you what happened in between
Write in the last
Fertilizer toward is a focus on principle, source code, development skills of technical public number, number of original thematic source code analysis, real scene source code principle combat (key).Scan the following QR codePay attention to fat, let should build rocket you, no longer screw!