Groovy是一種基于JVM的動態語言,可以與MyBatis框架協同工作。下面是一個簡單的示例,展示了如何在Groovy中使用MyBatis進行數據庫操作。
首先,需要在項目中添加Groovy和MyBatis的依賴。在Maven項目的pom.xml文件中添加以下依賴:
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>3.0.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
創建一個名為UserMapper.groovy
的Groovy腳本,用于定義數據庫操作接口:
package com.example
interface UserMapper {
User getUserById(int id)
List<User> getUsers()
}
在resources/mapper
目錄下創建一個名為UserMapper.xml
的文件,用于描述數據庫操作的具體實現:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.UserMapper">
<select id="getUserById" resultType="com.example.User">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="getUsers" resultType="com.example.User">
SELECT * FROM user
</select>
</mapper>
創建一個名為UserService.groovy
的Groovy腳本,用于封裝數據庫操作:
package com.example
import org.apache.ibatis.session.SqlSession
import org.apache.ibatis.session.SqlSessionFactory
class UserService {
SqlSessionFactory sqlSessionFactory
UserService(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory
}
User getUserById(int id) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper)
return userMapper.getUserById(id)
}
}
List<User> getUsers() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper)
return userMapper.getUsers()
}
}
}
在主程序中,創建SqlSessionFactory
實例,并使用UserService
進行數據庫操作:
import com.example.UserService
import org.apache.ibatis.io.Resources
import org.apache.ibatis.session.SqlSessionFactoryBuilder
public class Main {
public static void main(String[] args) throws Exception {
String resource = "mapper/UserMapper.xml"
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream)
UserService userService = new UserService(sqlSessionFactory)
User user = userService.getUserById(1)
System.out.println("User: " + user)
List<User> users = userService.getUsers()
System.out.println("Users: " + users)
}
}
}
這樣,就可以在Groovy中通過MyBatis進行數據庫操作了。