java ee 创建Dog类,在其中添加name和age属性。搭建mybatis框架,通过mybatis框架对dog类进行简单查找操作
时间: 2024-02-27 07:53:55 浏览: 163
首先需要在Java EE项目中引入Mybatis依赖,然后创建Dog类:
```java
public class Dog {
private String name;
private int age;
// 构造函数、getter和setter方法
}
```
接下来在MyBatis的配置文件中添加Dog类的映射:
```xml
<!-- Dog类的映射 -->
<mapper namespace="com.example.mapper.DogMapper">
<resultMap id="dogResultMap" type="com.example.model.Dog">
<id property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="findDogByName" resultMap="dogResultMap">
SELECT name, age FROM Dog WHERE name = #{name}
</select>
</mapper>
```
然后在Java EE项目中创建DogMapper接口,并添加一个findDogByName()方法:
```java
public interface DogMapper {
Dog findDogByName(String name);
}
```
接着在Java EE项目中创建MybatisUtil类,用于获取SqlSession实例:
```java
public class MybatisUtil {
private static SqlSessionFactory sessionFactory;
static {
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sessionFactory.openSession();
}
}
```
最后,在Java EE项目中调用DogMapper接口中的findDogByName()方法:
```java
public class Main {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtil.getSession();
DogMapper dogMapper = sqlSession.getMapper(DogMapper.class);
Dog dog = dogMapper.findDogByName("Tom");
System.out.println(dog.getName() + " " + dog.getAge());
sqlSession.close();
}
}
```
这样就完成了通过Mybatis框架对Dog类进行简单查找操作。
阅读全文