在Spring框架與MyBatis的整合中,SM編程(Spring + MyBatis)是一種常見的DAO層開發(fā)方式。
下面是一個簡單的示例:
首先,確保已經(jīng)正確配置了Spring框架和MyBatis。
1. 創(chuàng)建DAO接口:在DAO層定義一個接口,用于聲明數(shù)據(jù)訪問操作的方法。例如,創(chuàng)建一個UserDao接口:
public interface UserDao {User getUserById(int id);
List<User> getAllUsers();
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
2. 創(chuàng)建DAO接口的實現(xiàn)類:實現(xiàn)上述接口,并使用MyBatis來執(zhí)行相應(yīng)的SQL語句。例如,創(chuàng)建一個UserDaoImpl類:
@Repositorypublic class UserDaoImpl implements UserDao {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Override
public User getUserById(int id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
return session.selectOne("getUserById", id);
}
}
@Override
public List<User> getAllUsers() {
try (SqlSession session = sqlSessionFactory.openSession()) {
return session.selectList("getAllUsers");
}
}
@Override
public void addUser(User user) {
try (SqlSession session = sqlSessionFactory.openSession()) {
session.insert("addUser", user);
session.commit();
}
}
@Override
public void updateUser(User user) {
try (SqlSession session = sqlSessionFactory.openSession()) {
session.update("updateUser", user);
session.commit();
}
}
@Override
public void deleteUser(int id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
session.delete("deleteUser", id);
session.commit();
}
}
}
3. 配置MyBatis的Mapper文件:在resources目錄下創(chuàng)建一個與DAO接口相對應(yīng)的Mapper XML文件(例如UserMapper.xml),并定義SQL語句。示例:
<mapper namespace="com.example.dao.UserDao"><select id="getUserById" resultType="com.example.entity.User">
SELECT * FROM users WHERE id = #{id}
</select>
<select id="getAllUsers" resultType="com.example.entity.User">
SELECT * FROM users
</select>
<insert id="addUser" parameterType="com.example.entity.User">
INSERT INTO users (name, email) VALUES (#{name}, #{email})
</insert>
<update id="updateUser" parameterType="com.example.entity.User">
UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
4. 配置Spring的Bean:在Spring配置文件中,將`UserDaoImpl注入為一個Bean,并配置MyBatis的相關(guān)設(shè)置。示例:
<bean id="userDao" class="com.example.dao.UserDaoImpl"><property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:com/example/mappers/*.xml" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 設(shè)置數(shù)據(jù)庫相關(guān)配置 -->
</bean>
通過以上步驟,你就可以在應(yīng)用中使用UserDao接口的實現(xiàn)類進行數(shù)據(jù)庫訪問操作了,同時Spring和MyBatis會進行整合并提供事務(wù)管理等功能。