我使用SpringBoot web和Morphia DAO(使用MongoDB)创建了一个REST web服务。
正如我在MySQL上使用Hibernate时所做的那样,我希望使用通用实体、存储库和endpoint,以便只需设置实体、继承存储库和服务,并将生成的CRUD用于REST调用。
它几乎完成了,但是我在使用吗啡对我的实体进行通用更新时遇到了一个问题。到目前为止,我所看到的一切都在谈论手动设置具有必须更改的字段的请求;但是在Hibernate的方式中,我们只是设置了Id字段,称为持久性(),它会自动知道数据库中发生了什么变化并应用了变化。
下面是一些代码。
BaseEntity。Java语言
package org.beep.server.entity;
import org.mongodb.morphia.annotations.Entity;
@Entity
abstract public class BaseEntity {
public static class JsonViewContext {
public interface Summary {}
public interface Detailed extends Summary{}
}
protected String id;
public void setId(String id) {
this.id = id;
}
}
使用者java(我最后的实体之一)
package org.beep.server.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.*;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.mongodb.morphia.annotations.*;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.FormParam;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
@Entity
@Indexes(
@Index(value="identifier", fields=@Field("email"))
)
@Builder
@NoArgsConstructor
@AllArgsConstructor
final public class User extends BaseEntity {
/**
* User's id
*/
@Id
@JsonView(JsonViewContext.Summary.class)
private String id;
/**
* User's email address
*/
@Getter @Setter
@JsonView(JsonViewContext.Summary.class)
@FormParam("email")
@Indexed
@Email
private String email;
/**
* User's hashed password
*/
@Getter
@JsonView(JsonViewContext.Detailed.class)
@FormParam("password")
@NotEmpty
private String password;
/**
* Sets the password after having hashed it
* @param clearPassword The clear password
*/
public void setPassword(String clearPassword) throws NoSuchAlgorithmException, InvalidKeySpecException {
PasswordEncoder encoder = new BCryptPasswordEncoder();
String hashedPassword = encoder.encode(clearPassword);
setHashedPassword(hashedPassword);
}
/**
* Directly sets the hashed password, whithout hashing it
* @param hashedPassword The hashed password
*/
protected void setHashedPassword(String hashedPassword) {
this.password = hashedPassword;
}
/**
* Converts the user to a UserDetail spring instance
*/
public UserDetails toUserDetails() {
return new org.springframework.security.core.userdetails.User(
getEmail(),
getPassword(),
true,
true,
true,
true,
AuthorityUtils.createAuthorityList("USER")
);
}
}
实体存储。java(我的基本存储库,继承自Morphia one)
package org.beep.server.repository;
import org.beep.server.entity.BaseEntity;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.dao.BasicDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
public class EntityRepository<Entity extends BaseEntity> extends BasicDAO<Entity, ObjectId> {
@Autowired
protected EntityRepository(Datastore ds) {
super(ds);
}
}
UserRepository.java(我的用户库)
package org.beep.server.repository;
import org.beep.server.entity.User;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.dao.BasicDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends EntityRepository<User> {
@Autowired
protected UserRepository(Datastore ds) {
super(ds);
}
}
实体服务。java(通用服务,从Restendpoint使用)
package org.beep.server.service;
import org.beep.server.entity.BaseEntity;
import org.beep.server.exception.EntityNotFoundException;
import org.beep.server.exception.UserEmailAlreadyExistsException;
import org.beep.server.repository.EntityRepository;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import java.util.List;
public abstract class EntityService<Entity extends BaseEntity, Repository extends EntityRepository> implements ServiceInterface<Entity> {
protected Repository repository;
public EntityService(Repository repository) {
this.repository = repository;
}
/**
* {@inheritDoc}
*/
public Entity create(Entity entity) throws UserEmailAlreadyExistsException {
repository.save(entity);
return entity;
}
/**
* {@inheritDoc}
*/
public void delete(String id) throws EntityNotFoundException {
//repository.deleteById(id).;
}
/**
* {@inheritDoc}
*/
public List<Entity> findAll() {
return repository.find().asList();
}
/**
* {@inheritDoc}
*/
public Entity findOneById(String id) throws EntityNotFoundException {
return (Entity) repository.get(id);
}
/**
* {@inheritDoc}
*/
public Entity update(String id, Entity entity) {
// Try to get the old entity, and to set the Id on the inputed one
// But how can I merge the two ? If I persist like that, I will just have the modified fields, others
// will be set to null...
Entity oldEntity = (Entity) repository.get(id);
entity.setId(id);
repository.save(entity);
// Create update operations works, but I have to set the changing fields manually...
// not so compatible with generics !
/*final Query<Entity> updateSelection = repository.createQuery().filter("_id",id);
repository.createUpdateOperations().
repository.update(updateSelection,entity);*/
return entity;
}
}
用户服务。Java语言
package org.beep.server.service;
import org.beep.server.entity.Message;
import org.beep.server.entity.User;
import org.beep.server.exception.EntityNotFoundException;
import org.beep.server.exception.UserEmailAlreadyExistsException;
import org.beep.server.repository.UserRepository;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.ws.rs.BadRequestException;
import java.util.List;
import java.util.Optional;
@Service
public class UserService extends EntityService<User, UserRepository> {
@Autowired
public UserService(UserRepository repository) {
super(repository);
}
}
RestResource.java(我的基本Restendpoint)
package org.beep.server.api.rest.v1;
import com.fasterxml.jackson.annotation.JsonView;
import org.beep.server.entity.BaseEntity;
import org.beep.server.entity.User;
import org.beep.server.entity.BaseEntity;
import org.beep.server.exception.EntityNotFoundException;
import org.beep.server.exception.UserEmailAlreadyExistsException;
import org.beep.server.service.EntityService;
import org.beep.server.service.ServiceInterface;
import org.beep.server.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
public class RestResource<Entity extends BaseEntity, Service extends EntityService> {
protected Service service;
// Default constructor private to avoid blank constructor
protected RestResource() {
this.service = null;
}
/**
* Creates an object
* @param object Object to create
* @return The newly created object
*/
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@JsonView(BaseEntity.JsonViewContext.Detailed.class)
Entity create(@RequestBody @Valid Entity object) throws UserEmailAlreadyExistsException {
return service.create(object);
}
/**
* Deletes an object from its id
* @param id Object to delete id
* @return The deleted object
* @throws EntityNotFoundException
*/
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
@JsonView(BaseEntity.JsonViewContext.Detailed.class)
User delete(@PathVariable("id") String id) throws EntityNotFoundException {
service.delete(id);
return new User();
}
/**
* Gets all the objects
* @return All the objects
*/
@RequestMapping(method = RequestMethod.GET)
@JsonView(BaseEntity.JsonViewContext.Summary.class)
List<Entity> findAll() {
return service.findAll();
}
/**
* Finds one object from its id
* @param id The object to find id
* @return The corresponding object
* @throws EntityNotFoundException
*/
@RequestMapping(value = "{id}", method = RequestMethod.GET)
@JsonView(BaseEntity.JsonViewContext.Detailed.class)
Entity findById(@PathVariable("id") String id) throws EntityNotFoundException {
return service.findOneById(id);
}
/**
* Updates an object
* @param object The object to update
* @return The updated object
*/
@RequestMapping(value = "{id}", method = RequestMethod.PUT)
@JsonView(BaseEntity.JsonViewContext.Detailed.class)
Entity update(@PathVariable String id, @RequestBody @Valid Entity object) {
return service.update(id, object);
}
/**
* Handles the EntityNotFound exception to return a pretty 404 error
* @param ex The concerned exception
*/
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleEntityNotFound(EntityNotFoundException ex) {
}
/**
* Handles the REST input validation exceptions to return a pretty 400 bad request error
* with more info
* @param ex The validation exception
* @return A pretty list of the errors in the form
*/
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public List<ObjectError> handleValidationFailed(MethodArgumentNotValidException ex) {
// TODO : Check and improve the return of this method according to the front
// The concept is to automatically bind the error dans the failed parameter
return ex.getBindingResult().getAllErrors();
}
}
你遇到了莫菲娅的一个难题。根据上面发布的代码,您应该在此处查看合并方法。
需要记住的重要一点是,这不是深度合并,只是顶级字段,如果您有复杂的数据对象,这可能不会有帮助。
它基本上是这样工作的:
T实体-
T实体的标准转换规则适用于-
对于任何泛型实体的深度合并,它需要您自己使用自定义方法来处理。
这是关于SO的另一个问题的一个很好的例子,在Spring中使用JSON部分处理深度合并,而不是使用org处理复杂实体。科德豪斯。杰克逊。地图ObjectMapper。它应该很容易适应你的问题。
如果这两种方法都对您没有帮助,请在我的回答中进行评论,我们可以制定出一种适合您的自定义递归方法。希望这有帮助。
问题内容: 因此,我不确定如何问这个问题,因为似乎很容易找到这个问题的答案。 我有3张桌子;ContentHeader,ContentType1和ContentType2。ContentHeader具有主自动递增键。ContentType1和ContentType2都维护指向ContentHeader的主键的外键。这些外键也是它们各自表的主键。 我创建了四个类: 尝试生成架构时,这将引发空指针。我
我需要在另一个相关实体更新后对一个实体执行更新。 我有两个实体:和,关系为1:N。两者都有字段。状态取决于所有子状态字段。因此,如果更新了一个,我需要重新计算的新状态并持久化/更新它。 我实现了一个监听器: 监听器在中进行了注释,并且正在正确调用它。但是,在流程完成后,仍然保持旧状态,即使使用正确的新状态调用。
问题内容: 我将SpringJPARepository与hibernate一起使用,并且对实体更新有一个问题。我通过传递单个实体来调用jparepository.save(entity),但在跟踪日志中,我也可以看到针对数据库中其他行发出的更新语句。在调用save之前,我有一个findAll并且某些实体的值正在更改。但是我只传递了一个要保存的实体,但是仍然保存了所有更新的实体。您能提供有关此信息吗
问题内容: 这是表 用户数 和代码.. 问题答案: Ladislav的答案已更新为使用DbContext(在EF 4.1中引入):
我有一个User类,它有一些附加属性: 现在,如果我调用一些方法来改变其中一个房子(例如改变它的名称属性),如果我调用,我仍然会得到房子的旧值: 我如何确保它总是更新?
当我尝试更新一个实体的一个字段时,我是新来的,我注意到在日志中Hibernate执行两个查询,在更新之前,它会对所有字段进行SELECT。可以吗?为什么Hibernate执行SELECT?我如何用一个UPDATE查询更新一个字段?此外,当我试图更新一个实体中的单个标题时,它有另一个嵌套实体,我最终得到了一堆SELECT。我认为这对性能不好,或者我错了? 在互联网上,我找到了使用 @Modifyin