创建Dog类,在其中添加name和age属性。创建对应数据库,根据name和 age属性,使用MyBatis查询和更新Dog类,要求当name和age属性的值为空时,去掉相应的筛选添加(使用动态SQL实现)。
时间: 2024-01-22 17:21:00 浏览: 31
以下是创建Dog类并添加name和age属性的Java代码:
```java
public class Dog {
private Integer id;
private String name;
private Integer age;
// getters and setters
}
```
接下来,我们需要创建对应的数据库表,并使用MyBatis进行查询和更新操作。以下是相应的SQL语句:
```sql
CREATE TABLE `dog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
INSERT INTO `dog` (`name`, `age`) VALUES ('Tom', 3);
INSERT INTO `dog` (`name`, `age`) VALUES ('Jerry', 2);
INSERT INTO `dog` (`name`, `age`) VALUES ('Spike', 5);
```
然后,我们需要使用MyBatis框架进行查询和更新操作。以下是对应的Mapper接口和XML文件:
DogMapper.java
```java
public interface DogMapper {
List<Dog> selectDogs(@Param("name") String name, @Param("age") Integer age);
void updateDog(Dog dog);
}
```
dogMapper.xml
```xml
<mapper namespace="com.example.mapper.DogMapper">
<select id="selectDogs" parameterType="map" resultMap="dogResultMap">
SELECT * FROM dog WHERE 1=1
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</select>
<update id="updateDog" parameterType="com.example.model.Dog">
UPDATE dog
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
WHERE id = #{id}
</update>
<resultMap id="dogResultMap" type="com.example.model.Dog">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</resultMap>
</mapper>
```
其中,查询操作使用了动态SQL,当name和age属性的值为空时,去掉相应的筛选条件。
接下来,我们可以通过MyBatis框架进行查询和更新操作。以下是示例代码:
```java
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
DogMapper dogMapper = sqlSession.getMapper(DogMapper.class);
// 查询所有狗狗
List<Dog> dogs = dogMapper.selectDogs(null, null);
System.out.println(dogs);
// 查询名字为Tom的狗狗
dogs = dogMapper.selectDogs("Tom", null);
System.out.println(dogs);
// 更新名字为Jerry的狗狗的年龄为3岁
Dog dog = new Dog();
dog.setId(2);
dog.setAge(3);
dogMapper.updateDog(dog);
// 查询年龄大于等于5岁的狗狗
dogs = dogMapper.selectDogs(null, 5);
System.out.println(dogs);
} finally {
sqlSession.close();
}
```
以上示例代码演示了如何使用MyBatis框架进行查询和更新操作,并且使用了动态SQL实现了条件判断。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)