在多对象层次结构中设置分配

如何解决在多对象层次结构中设置分配

我在使用 optaplanner 分配产品时遇到问题,我正在按照以下层次结构实现类,Plan -> AvailableProduct -> AvailableProductTask ->assignee。我想设置包含在上述对象层次结构中的受让人字段,我尝试了文档中给出的几个示例,包括员工名册。任何人都可以建议在 AvailableProductTask 类中设置受让人的解决方案吗? POJO代码如下...

    import java.util.ArrayList;
    import java.util.List;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EnumType;
    import javax.persistence.Enumerated;
    import javax.persistence.FetchType;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    
    import org.apache.commons.lang3.builder.EqualsBuilder;
    import org.apache.commons.lang3.builder.HashCodeBuilder;
    import org.apache.commons.lang3.builder.ToStringBuilder;
    
    @Entity
    @Table(name = "plan")
    public class Plan extends BaseEntity<Long> {
    
        private static final long serialVersionUID = -5734441725217207470L;
    
        @Column(length = 255,nullable = false)
        private String name;
    
        @Column(length = 255,nullable = false)
        private String description;
    
        private Long parentPlanId;
    
        @Column(nullable = false,columnDefinition = "varchar(32) default 'TODO'")
        @Enumerated(value = EnumType.STRING)
        private PlanStatus status;
    
        @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
        @JoinColumn(name = "plan_id")
        private List<AvailableUser> users;
    
        @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
        @JoinColumn(name = "plan_id")
        private List<AvailableCustomerSla> slas;
    
        @OneToMany
        @JoinColumn(name = "plan_Id")
        private List<AvailableProduct> products;
    
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(final String name) {
            this.name = name;
        }
    
        /**
         * @return the description
         */
        public String getDescription() {
            return description;
        }
    
        /**
         * @param description the description to set
         */
        public void setDescription(final String description) {
            this.description = description;
        }
    
        /**
         * @return the parentPlanId
         */
        public Long getParentPlanId() {
            return parentPlanId;
        }
    
        /**
         * @param parentPlanId the parentPlanId to set
         */
        public void setParentPlanId(final Long parentPlanId) {
            this.parentPlanId = parentPlanId;
        }
    
        /**
         * @return the status
         */
        public PlanStatus getStatus() {
            return status;
        }
    
        /**
         * @return the users
         */
        public List<AvailableUser> getUsers() {
            return users;
        }
    
        /**
         * @param status the status to set
         */
        public void setStatus(final PlanStatus status) {
            this.status = status;
        }
    
        /**
         * @param users the users to set
         */
        public void setUsers(final List<AvailableUser> users) {
            this.users = users;
        }
    
        /**
         * @return the slas
         */
        public List<AvailableCustomerSla> getSlas() {
            return slas;
        }
    
        /**
         * @param slas the slas to set
         */
        public void setSlas(List<AvailableCustomerSla> slas) {
            this.slas = slas;
        }
    
        /**
         * @return the products
         */
        public List<AvailableProduct> getProducts() {
            return products;
        }
    
        /**
         * @param products the products to set
         */
        public void setProducts(List<AvailableProduct> products) {
            this.products = products;
        }
    
        /**
         * Adds a single available product to the list of products
         * @param product the product to add
         */
        public void addAvailableProduct(AvailableProduct product) {
            if (null == product) {
                return;
            }
            if (null == this.products) {
                this.products = new ArrayList<>();
            }
            this.products.add(product);
        }
    
        @Override
        public final boolean equals(final Object object) {
            if (object == null) {
                return false;
            }
            if (object == this) {
                return true;
            }
            if (!(object instanceof Plan)) {
                return false;
            }
            final Plan plan = (Plan) object;
            return new EqualsBuilder() //
                    .append(this.getId(),plan.getId()) //
                    .isEquals();
        }
    
        @Override
        public final int hashCode() {
            return new HashCodeBuilder() //
                    .append(getId()) //
                    .hashCode();
        }
    
        @Override
        public String toString() {
            return new ToStringBuilder(this) //
                    .append("Id",getId()) //
                    .append("Name",getName()) //
                    .append("Description",getDescription()) //
                    .append("ParentPlanId",getParentPlanId()) //
                    .append("Status",getStatus()) //
                    .append("Users",getUsers()) //
                    .append("Products",getProducts()) //
                    .toString();
        }
    }
    
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;

@Entity
@Table(uniqueConstraints = {
    @UniqueConstraint(columnNames = { "plan_id","productId" }) })
@PlanningSolution
public class AvailableProduct extends BaseEntity<Long> {

    private static final long serialVersionUID = -4463281008771600521L;

    @Column(nullable = false)
    private String productId;

    @Column(nullable = false)
    private String categoryId;

    @OneToMany
    @JoinColumn(name = "plan_available_product_id")
    @PlanningEntityCollectionProperty
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<AvailableProductTask> tasks;

    @OneToMany
    @JoinColumn(name = "plan_available_product_id")
    private List<AvailableProductCustomerSLA> availableProductCustomerSLAs;

    @ElementCollection
    @ProblemFactCollectionProperty
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<Integer> facts;

    @PlanningScore
    private HardSoftScore score;


    /**
     * Argument free constructor
     */
    public AvailableProduct() {

    }

    /**
     * Constructor for create available product instance.
     *
     * @param productId Id of the product.
     * @param categoryId Id of the category.
     */
    public AvailableProduct(final String productId,final String categoryId) {
        this.productId = productId;
        this.categoryId = categoryId;
        this.tasks = new ArrayList<>();
    }


    public List<Integer> getFacts() {
        return facts;
    }

    public void setFacts(List<Integer> facts) {
        this.facts = facts;
    }

    /**
     * @return the score
     */
    public HardSoftScore getScore() {
        return score;
    }

    /**
     * @param score the score to set
     */
    public void setScore(HardSoftScore score) {
        this.score = score;
    }


    /**
     * @return the productId
     */
    public String getProductId() {
        return productId;
    }

    /**
     * @param productId the productId to set
     */
    public void setProductId(final String productId) {
        this.productId = productId;
    }

    /**
     * @return the categoryId
     */
    public String getCategoryId() {
        return categoryId;
    }

    /**
     * @param categoryId the categoryId to set
     */
    public void setCategoryId(final String categoryId) {
        this.categoryId = categoryId;
    }

    /**
     * @return the tasks
     */
    public List<AvailableProductTask> getTasks() {
        return tasks;
    }

    /**
     * @param tasks the tasks to set
     */
    public void setTasks(final List<AvailableProductTask> tasks) {
        this.tasks = tasks;
    }

    /**
     * Adds a single task to the list of tasks
     * @param task the task to add
     */
    public void addTasks(final AvailableProductTask task) {
        if (null == task) {
            return;
        }
        if (null == this.tasks) {
            this.tasks = new ArrayList<>();
        }
        this.tasks.add(task);
    }

    /**
     * @return the availableProductCustomerSLAs
     */
    public List<AvailableProductCustomerSLA> getAvailableProductCustomerSLAs() {
        return availableProductCustomerSLAs;
    }

    /**
     * @param availableProductCustomerSLAs the availableProductCustomerSLAs to set
     */
    public void setAvailableProductCustomerSLAs(
            List<AvailableProductCustomerSLA> availableProductCustomerSLAs) {
        this.availableProductCustomerSLAs = availableProductCustomerSLAs;
    }

    /**
     * Adds a single availableProductCustomerSLA to the list of slas
     * @param availableProductCustomerSLA the availableProductCustomerSLA to add
     */
    public void addAvailableProductCustomerSLA(
            final AvailableProductCustomerSLA availableProductCustomerSLA) {
        if (null == availableProductCustomerSLA) {
            return;
        }
        if (null == this.availableProductCustomerSLAs) {
            this.availableProductCustomerSLAs = new ArrayList<>();
        }
        this.availableProductCustomerSLAs.add(availableProductCustomerSLA);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean equals(final Object object) {
        if (object == null) {
            return false;
        }
        if (object == this) {
            return true;
        }
        if (!(object instanceof AvailableProduct)) {
            return false;
        }
        final AvailableProduct rhs = (AvailableProduct) object;
        return new EqualsBuilder() //
                .append(this.getId(),rhs.getId()) //
                .isEquals();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final int hashCode() {
        return new HashCodeBuilder() //
                .append(getId()) //
                .hashCode();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return new ToStringBuilder(this) //
                .append("Id",getId()) //
                .append("ProductId",getProductId()) //
                .append("CategoryId",getCategoryId()) //
                .append("Tasks",getTasks()) //
                .append("AvailableCustomerSlas",getAvailableProductCustomerSLAs()) //
                .toString();
    }

}
    
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.domain.variable.PlanningVariable;

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {
    "plan_available_product_id","productId","localeId","type" }) })
@PlanningEntity
public class AvailableProductTask extends BaseEntity<Long> {

    private static final long serialVersionUID = 2978786872246225416L;

    @Column(nullable = false)
    private String productId;

    @Column(nullable = false)
    private String localeId;

    @Column(nullable = false)
    private Type type;

    @Column(nullable = false)
    private TaskStatus status;

    private int taskId;

    @PlanningVariable(valueRangeProviderRefs = "taskUsersRange")
    private AvailableProductTaskUser assignee;

    @OneToMany
    @JoinColumn(name = "plan_available_product_task_id")
    @LazyCollection(LazyCollectionOption.FALSE)
    @ProblemFactCollectionProperty
    @ValueRangeProvider(id = "taskUsersRange")
    private List<AvailableProductTaskUser> taskUsers;

    /**
     * Argument constructor
     */
    public AvailableProductTask() {
    }

    /**
     * Constructor for available product task.
     *
     * @param productId Id of the product for this task.
     * @param localeId Id of the locale of product for the task.
     * @param type Type of the task for the product.
     * @param status Status of the task for the product.
     */
    public AvailableProductTask(final String productId,final String localeId,//
            final Type type,final TaskStatus status) {
        this.productId = productId;
        this.localeId = localeId;
        this.type = type;
        this.status = status;
    }

    /**
     * @return the productId
     */
    public String getProductId() {
        return productId;
    }

    /**
     * @param productId the productId to set
     */
    public void setProductId(final String productId) {
        this.productId = productId;
    }

    /**
     * @return the localeId
     */
    public String getLocaleId() {
        return localeId;
    }

    /**
     * @param localeId the localeId to set
     */
    public void setLocaleId(final String localeId) {
        this.localeId = localeId;
    }

    /**
     * @return the type
     */
    public Type getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(final Type type) {
        this.type = type;
    }

    /**
     * @return the status
     */
    public TaskStatus getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(final TaskStatus status) {
        this.status = status;
    }

    /**
     * @return the taskId
     */
    public int getTaskId() {
        return taskId;
    }

    /**
     * @param taskId the taskId to set
     */
    public void setTaskId(final int taskId) {
        this.taskId = taskId;
    }

    /**
     * @return the assignee
     */
    public AvailableProductTaskUser getAssignee() {
        return assignee;
    }

    /**
     * @param assignee the assignee to set
     */
    public void setAssignee(final AvailableProductTaskUser assignee) {
        this.assignee = assignee;
    }

    /**
     * @return the taskUsers
     */
    public List<AvailableProductTaskUser> getTaskUsers() {
        return taskUsers;
    }

    /**
     * @param taskUsers the taskUsers to set
     */
    public void setTaskUsers(final List<AvailableProductTaskUser> taskUsers) {
        this.taskUsers = taskUsers;
    }

    /**
     * Adds a single availableProductTaskUser to the list of task users
     * @param taskUser the taskUser to add
     */
    public void addAvailableProductTaskUser(final AvailableProductTaskUser taskUser) {
        if (null == taskUser) {
            return;
        }
        if (null == this.taskUsers) {
            this.taskUsers = new ArrayList<>();
        }
        this.taskUsers.add(taskUser);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean equals(final Object object) {
        if (object == null) {
            return false;
        }
        if (object == this) {
            return true;
        }
        if (!(object instanceof AvailableProductTask)) {
            return false;
        }
        final AvailableProductTask rhs = (AvailableProductTask) object;
        return new EqualsBuilder() //
                .append(this.getId(),getProductId()) //
                .append("LocaleId",getLocaleId()) //
                .append("Type",getType()) //
                .append("Status",getStatus()) //
                .append("TaskId",getTaskId()) //
                .append("Assignee",getAssignee()) //
                .toString();
    }

}

    /**
     * Start the execution of creating a plan.
     *
     * @param id Id of the plan
     * @return Http Status Ok.
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @SuppressWarnings("unused")
    @PutMapping("/plans/{id}/execute")
    public ResponseEntity<Plan> execute(@PathVariable("id") final Long id) {
        Assert.notNull(id,"id cannot be null");
        final Optional<Plan> plan = planRepository.findById(id);
        if (!plan.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        List<AvailableProduct> products = plan.get().getProducts();
        List<AvailableProduct> updatedProducts = Lists.newArrayList();
        products.stream().forEach(product -> {
            SolverJob<AvailableProduct,Long> solverJob = solverManager.solveAndListen(product.getId(),availableProductService::findById,availableProductService::save);
            try {
                // Wait until the solving ends
                AvailableProduct solution = solverJob.getFinalBestSolution();
                AvailableProduct product2 = availableProductRepository.save(solution);
                product2.setTasks(solution.getTasks());
                scoreManager.updateScore(product2); // Sets the score
                updatedProducts.add(product2);
            } catch (InterruptedException | ExecutionException e) {
                throw new IllegalStateException("Solving failed.",e);
            }
        });
        Plan planSolution = plan.get();
        planSolution.setProducts(updatedProducts);
        return ResponseEntity.status(HttpStatus.OK).body(planSolution);
    }

import java.util.List;

import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;

import com.etilize.burraq.planning.service.product.AvailableProduct;
import com.etilize.burraq.planning.service.product.AvailableProductTask;

public class ScoreCalculator
    implements EasyScoreCalculator<AvailableProduct> {

  // For calculating score
  @Override
  public HardSoftScore calculateScore(AvailableProduct availableProduct) {
      int hardScore = 0;
      int softScore = 0;
      List<AvailableProductTask> tasks = availableProduct.getTasks();
      for (AvailableProductTask task1: tasks) {
          for (AvailableProductTask task2: tasks) {
              if (task1.getAssignee() != null && task1.getAssignee().equals(task2.getAssignee())) {
                  hardScore--;
              }
          }
      }
      return HardSoftScore.of(hardScore,softScore);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-