jpa问题

集合操作实现题目
 
Order,OrderItem,是1对多的双向关联关系。
a)         这2个类用于网络传输
b)        复写equals,Hashcode,Comparaor,toString方法
c)         在order中写一个方法新增一条Orderitem,考虑双向关联,考虑null
d)        在OrderItem中写一个方法,setOrder,考虑双向关联,考虑null
e)         采用Springboot+JPA的方式实现根据用户传入的Orderid,返回Order(但不返回OrderItem的集合)
f)          采用工具自动根据表自动生成类,在类中ManyToOne等注解被自动生成。

 

项目结构如下:

 

 

配置文件

 


server.port=8081


spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/db_crm?serverTimezone=GMT%2B8&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8&useSSL=false

spring.datasource.username=root

spring.datasource.password=an341221

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

 

BbbApplication
package com.example.bbb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
public class BbbApplication {

	public static void main(String[] args) {
		SpringApplication.run(BbbApplication.class, args);
	}

}

 

 

Order类

package com.example.bbb;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
@Data
@Entity
@Table(name="t_order")
public class Order implements Comparator,Serializable {

    private static final long serialVersionUID = -7849861349440231763L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="order_id", length = 100)
    private Long id;

    @Column(name="order_name")
    private String name;


    @JsonIgnoreProperties
    @OneToMany(mappedBy="order",fetch=FetchType.EAGER,cascade={CascadeType.ALL})
    private Set<OrderItem> set = new HashSet<OrderItem>(0);

    public void setSet(Set<OrderItem> set) {
            this.set = set;


    }

    public Set<OrderItem> getSet() {
        return set;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void addOrderItem(OrderItem item) {
        if(null!=item&&!set.contains(item)) {
            item.setOrder(this);
            this.set.add(item);
        }
    }

    @Override
    public int compare(Object o1, Object o2) {
        if(o1 == null || o2 == null)
            return 0;
        Order o = (Order)o1;
        Order p = (Order)o2;
        return o.getName().toUpperCase().compareTo(p.getName().toUpperCase());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Order)) return false;

        Order order = (Order) o;

        if (id != null ? !id.equals(order.id) : order.id != null) return false;
        return name != null ? name.equals(order.name) : order.name == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }



}

Orderitem类

package com.example.bbb;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Comparator;

@Entity
@Table(name="t_order_item")
public class OrderItem implements Comparator,Serializable {

    private static final long serialVersionUID = -188903609403774903L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="order_item_id", length = 100)
    private Long id;

    @Column(name="order_item_name")
    private String name;

    @Column(name="order_id1")
    private Long orderId;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof OrderItem)) return false;

        OrderItem item = (OrderItem) o;

        if (id != null ? !id.equals(item.id) : item.id != null) return false;
        if (name != null ? !name.equals(item.name) : item.name != null) return false;
        return orderId != null ? orderId.equals(item.orderId) : item.orderId == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (orderId != null ? orderId.hashCode() : 0);
        return result;
    }

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(
            name = "order_id1",
            referencedColumnName = "order_id",insertable =false,updatable = false
    )
    @JsonIgnoreProperties
    private Order order;

    public void setOrder(Order order) {
        if(null!=order){
            this.order = order;
        }

    }
    public Order getOrder() {
        return order;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setOrderId(Long orderId) {
        this.orderId = orderId;
    }


    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Long getOrderId() {
        return orderId;
    }




    @Override
    public String toString() {
        return "OrderItem{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", orderId=" + orderId +
                '}';
    }

    @Override
    public int compare(Object o1, Object o2) {
        if(o1 == null || o2 == null)
            return 0;
        OrderItem o = (OrderItem)o1;
        OrderItem p = (OrderItem)o2;
        return o.getName().toUpperCase().compareTo(p.getName().toUpperCase());
    }

}

OrderDao类

package com.example.bbb;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface OrderDao extends JpaRepository<Order,Long> {

    @Query(value = "select order_id,order_name from t_order  where order_id=?1",nativeQuery = true)
    Order findByOrderId(Long  id);


}

OrderItemDao类

package com.example.bbb;

import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderItemDao  extends JpaRepository<OrderItem,Long> {
}
TestServiceImpl类
package com.example.bbb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TestServiceImpl implements TestService{



    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Transactional
    @Override
    public void add() {

        Order order = new Order();
        order.setName("o3");

        OrderItem item = new OrderItem();
        item.setName("i31");

        OrderItem item1 = new OrderItem();
        item1.setName("i32");

        order.getSet().add(item);
        order.getSet().add(item1);

        item.setOrder(order);
        item1.setOrder(order);

        Order o = orderDao.save(order);
        item.setOrderId(o.getId());
        item1.setOrderId(o.getId());
        orderItemDao.save(item);
        orderItemDao.save(item1);

    }

    @Override
    public Order findByOrderId(Long id) {
        return orderDao.findByOrderId(id);
    }
}
TestController类

 

package com.example.bbb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/add")
    public void test(){
        testService.add();
    }

    @RequestMapping("/query")
    public void findByOrderId(){

        System.out.println(testService.findByOrderId(1L));

    }

}

 

 

项目启动的建表语句

Hibernate: 
    
    create table t_order (
       order_id bigint not null auto_increment,
        order_name varchar(255),
        primary key (order_id)
    ) engine=MyISAM
Hibernate: 
    
    create table t_order_item (
       order_item_id bigint not null auto_increment,
        order_item_name varchar(255),
        order_id1 bigint,
        primary key (order_item_id)
    ) engine=MyISAM
Hibernate: 
    
    alter table t_order_item 
       add constraint FK4421rqle7r4qiecv2uj5ec9kx 
       foreign key (order_id1) 
       references t_order (order_id)

 

插入数据库的字段

orderitem

order

 

 

没有OrderItem集合的查询结果如下

 

 

工具生成实体类,会产生中间类,需要手动复制下

建表语句

CREATE TABLE `example1` (
  `stu_id` int(11) NOT NULL DEFAULT '0',
  `name` VARCHAR(11) NOT NULL DEFAULT '',
  `course_id` int(11) NOT NULL DEFAULT '0',
  `grade` float DEFAULT NULL,
  PRIMARY KEY (`stu_id`,`course_id`)
) engine=INNODB;
CREATE TABLE `example2` (
  `id` int(11) NOT NULL,
  `stu_id` int(11) DEFAULT NULL,
  `course_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `f_ck` (`stu_id`,`course_id`),
  CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example1` (`stu_id`, `course_id`)
) engine=INNODB;
insert into example1 (stu_id,name,course_id,grade)values(1,'baidu',1,97.5),(2,'google',2,89);
insert into example2 (id,stu_id,course_id)values(1,1,1),(2,2,2);

生成的实体类

package com.example.demoforjpa.pojo;

import java.util.Objects;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;

@Entity
@Table(name = "example1", schema ="mysql")
public class Example1Entity {

  private Integer stuId;
  private String name;
  private Integer courseId;
  private Double grade;

  @Id
  @Column(name = "stu_id")
  public Integer getStuId() {
    return stuId;
  }

  public void setStuId(Integer stuId) {
    this.stuId = stuId;
  }

  @Basic
  @Column(name = "name")
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Id
  @Column(name = "course_id")
  public Integer getCourseId() {
    return courseId;
  }

  public void setCourseId(Integer courseId) {
    this.courseId = courseId;
  }

  @Basic
  @Column(name = "grade")
  public Double getGrade() {
    return grade;
  }

  public void setGrade(Double grade) {
    this.grade = grade;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Example1Entity that = (Example1Entity) o;
    return Objects.equals(stuId,that.stuId) &&
        Objects.equals(name,that.name) &&
        Objects.equals(courseId,that.courseId) &&
        Objects.equals(grade,that.grade);
  }

  @Override
  public int hashCode() {
    return Objects.hash(stuId, name,courseId, grade);
  }
}
package com.example.demoforjpa.pojo;

import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "example2", schema = "mysql")
public class Example2Entity {

  private Integer id;
  private Integer stuId;
  private Integer courseId;
  private Example1Entity example1;

  @Column(name = "stu_id")
  public Integer getStuId() {
    return stuId;
  }

  public void setStuId(Integer stuId) {
    this.stuId = stuId;
  }

  @Column(name = "course_id")
  public Integer getCourseId() {
    return courseId;
  }

  public void setCourseId(Integer courseId) {
    this.courseId = courseId;
  }



  @Id
  @Column(name = "id")
  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Example2Entity that = (Example2Entity) o;
    return Objects.equals(id, that.id);
  }

  @Override
  public int hashCode() {
    return Objects.hash(id);
  }

  @ManyToOne
  @JoinColumns({
      @JoinColumn(name = "stu_id", referencedColumnName = "stu_id"),
      @JoinColumn(name = "course_id", referencedColumnName = "course_id")})
  public Example1Entity getExample1() {
    return example1;
  }

  public void setExample1(Example1Entity example1) {
    this.example1 = example1;
  }
}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读