2024年4月12日发(作者:)
jpa repository写like
在Spring Data JPA中,可以使用like关键字在Repository接
口的方法中进行模糊查询。以下是一个简单的例子:
假设有一个实体类 Person:
import ;
import tedValue;
import tionType;
import ;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = TY)
private Long id;
private String name;
// 其他属性和方法省略
}
1 / 3
然后,你可以在 PersonRepository 接口中定义一个方法来执行
模糊查询:
import
ository;
import ;
public interface PersonRepository extends
JpaRepository
// 使用 like 进行模糊查询
List
}
在上面的例子中,findByNameLike 方法将会根据 name 属性进
行模糊查询。Spring Data JPA 将会根据方法名自动生成相应的查询
语句。
在使用时,你可以直接调用该方法:
import
red;
import e;
import ;
2 / 3
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public List
// 调用模糊查询方法
return NameLike("%" +
name + "%");
}
}
在上面的例子中,findByNameLike("%" + name + "%") 将会查
找包含指定名称片段的所有 Person 实体。
请注意,% 符号是用于表示通配符的,它可以匹配零个或多个字
符。在这个例子中,"%name%" 表示匹配包含指定名称片段的任何字
符串。
3 / 3


发布评论