首页 \ 问答 \ onetomany unidirectional with jointable setup using jpa(onetomany unidirectional with jointable setup using jpa)

onetomany unidirectional with jointable setup using jpa(onetomany unidirectional with jointable setup using jpa)

我有两个实体,即客户关系和订单关系。 一个客户可以拥有多个订单。 因为我需要这种关系是单向的,所以我使用的是joinTable。

我可以使用JPA向我的客户实体添加条目。 我可以使用JPA向我的订单实体添加条目。

我想知道如何将两者连接在一起的数据。 假设我在客户表中有一个条目,在订单表中有两个条目。 我想将order表中的这两个条目与customer表中的一个条目相关联。

目前,我在jointable customer_order中没有看到任何条目。 我如何建立关联? 我想当我将订单添加到订单表中时,我将不得不以某种方式提及客户ID号。 不知道该怎么做。 在JPA中是否有标准查询?

谢谢。

客户类 -

@Entity
public class Customer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "generatorCustomer")
    @TableGenerator(name = "generatorCustomer", allocationSize = 1)
    @Column(name="customer_id")
    private Long id;
    public Long getId() {
        return id;
    }

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

    @OneToMany()
    @JoinTable (
        name="customer_order",
        joinColumns={ @JoinColumn(name="customer_id", referencedColumnName="customer_id") },
        inverseJoinColumns={ @JoinColumn(name="order_id", referencedColumnName="order_id", unique=true) }
    )
    private List<Order> orderList = new ArrayList<Order>();
    public List<Order> getOrderList() {
        if(this.orderList == null) {
            this.orderList = new ArrayList<Order>();
        }
        return this.orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    public void addOrder(Order order) {
        this.orderList.add(order);
    }

    /* other logic follows......... */
}

订单类 -

@Entity
public class Order implements Serializable {
@Id
@GeneratedValue
@Column(name="order_id")
private Long id;
public Long getId() {
    return id;
}

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

/* other logic follows......... */
}

客户表说明:

jbossql=# \d customer
Column   |         Type          |                        Modifiers
-------------+-----------------------+---------------------------------------------------------------
customer_id | bigint                | not null default nextval('customer_customer_id_seq'::regclass)
name        | character varying(50) | 
Indexes:
"customer_pkey" PRIMARY KEY, btree (customer_id)
Referenced by:
TABLE "customer_order" CONSTRAINT "fk8ef2f420ec016855" FOREIGN KEY (customer_id) REFERENCES customer(customer_id)

订单表说明:

jbossql=# \d order
Column   |  Type  | Modifiers 
------------+--------+-----------
order_id   | bigint | not null
value      | real   | 
Indexes:
"order_pkey" PRIMARY KEY, btree (order_id)
Referenced by:
TABLE "customer_order" CONSTRAINT "fk1e4828a98187660" FOREIGN KEY (order_id) REFERENCES order(order_id)

customer_order联合表描述:

jbossql=# \d customer_order
Column       |  Type  | Modifiers 
--------------+--------+-----------
customer_id  | bigint | not null
order_id     | bigint | not null
Indexes:
"customer_order_order_id_key" UNIQUE CONSTRAINT, btree (order_id)
Foreign-key constraints:
"fk1e4828a98187660" FOREIGN KEY (order_id) REFERENCES order(order_id)
"fk1e4828adba386b8" FOREIGN KEY (customer_id) REFERENCES customer(customer_id)

我可以在customer表中插入一个项目:

jbossql=# select * from customer;
customer_id | name 
-------------+-------------
1        | joe
(1 row)

我也可以将项目插入到oder表中:

jbossql=# select * from order;
order_id | value 
----------+-----------
1       |  1.8
2       |  0.5
(2 rows)

我以为customer_order表会自动填充,即hibernate会采取这种方式。 但似乎不是因为我的连接表是空的:

jbossql=# select * from customer_order;
customer_id | order_id 
-------------+-----------
(0 rows)

所以,我的目的是让这两个订单条目与客户乔相关联。

请帮忙。

  1. 我是否必须向customer_order表明确添加记录?
  2. 如果没有,我如何将项目插入订单表,以便我可以将该条目连接到特定客户?
  3. 我的映射是否正确在这个OneToMany [unidirection]关系的java文件中按预期工作
  4. 我正在使用JPA2和JBoss以及Hibernate。 你有任何代码参考TEST一对多的关系吗? 对完整项目或阅读材料的任何参考都会有所帮助。

谢谢你的期待。


I have two entities namely customer and order in a onetomany relationship. One customer can have multiple orders. Since i needed this relationship to be unidirectional, i am using a joinTable.

I am able to add entries to my customer entity using JPA. I am able to add entries to my order entity using JPA.

I am wondering how to connect the two together data. Let's say i have one entry in customer table and two entries in order table. I would like to associate these two entries in order table to the one entry in customer table.

Currently, i don't see any entries in my jointable customer_order. How do i make the association? I guess while i am adding the orders into the order table, i will have to mention the customer id number somehow. Not sure how to do that. Is there a criteria query for that in JPA?

Thanks.

Customer Class -

@Entity
public class Customer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "generatorCustomer")
    @TableGenerator(name = "generatorCustomer", allocationSize = 1)
    @Column(name="customer_id")
    private Long id;
    public Long getId() {
        return id;
    }

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

    @OneToMany()
    @JoinTable (
        name="customer_order",
        joinColumns={ @JoinColumn(name="customer_id", referencedColumnName="customer_id") },
        inverseJoinColumns={ @JoinColumn(name="order_id", referencedColumnName="order_id", unique=true) }
    )
    private List<Order> orderList = new ArrayList<Order>();
    public List<Order> getOrderList() {
        if(this.orderList == null) {
            this.orderList = new ArrayList<Order>();
        }
        return this.orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    public void addOrder(Order order) {
        this.orderList.add(order);
    }

    /* other logic follows......... */
}

Order Class -

@Entity
public class Order implements Serializable {
@Id
@GeneratedValue
@Column(name="order_id")
private Long id;
public Long getId() {
    return id;
}

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

/* other logic follows......... */
}

Customer table description:

jbossql=# \d customer
Column   |         Type          |                        Modifiers
-------------+-----------------------+---------------------------------------------------------------
customer_id | bigint                | not null default nextval('customer_customer_id_seq'::regclass)
name        | character varying(50) | 
Indexes:
"customer_pkey" PRIMARY KEY, btree (customer_id)
Referenced by:
TABLE "customer_order" CONSTRAINT "fk8ef2f420ec016855" FOREIGN KEY (customer_id) REFERENCES customer(customer_id)

Order Table description:

jbossql=# \d order
Column   |  Type  | Modifiers 
------------+--------+-----------
order_id   | bigint | not null
value      | real   | 
Indexes:
"order_pkey" PRIMARY KEY, btree (order_id)
Referenced by:
TABLE "customer_order" CONSTRAINT "fk1e4828a98187660" FOREIGN KEY (order_id) REFERENCES order(order_id)

customer_order joint table description:

jbossql=# \d customer_order
Column       |  Type  | Modifiers 
--------------+--------+-----------
customer_id  | bigint | not null
order_id     | bigint | not null
Indexes:
"customer_order_order_id_key" UNIQUE CONSTRAINT, btree (order_id)
Foreign-key constraints:
"fk1e4828a98187660" FOREIGN KEY (order_id) REFERENCES order(order_id)
"fk1e4828adba386b8" FOREIGN KEY (customer_id) REFERENCES customer(customer_id)

I am able to insert an item into the customer table:

jbossql=# select * from customer;
customer_id | name 
-------------+-------------
1        | joe
(1 row)

I am able to insert items into the oder table as well:

jbossql=# select * from order;
order_id | value 
----------+-----------
1       |  1.8
2       |  0.5
(2 rows)

I was thinking the customer_order table would automatically get populated i.e hibernate would take of that. But appears not because my jointable is empty:

jbossql=# select * from customer_order;
customer_id | order_id 
-------------+-----------
(0 rows)

So, my intention is to make those two order entries connected to customer joe.

Please help.

  1. Do i have to explicitly add a record to the customer_order table?
  2. If not, how do i insert items into order table so that i can connect that entry to a particular customer?
  3. Are my mappings right in the java files for this OneToMany [unidirection] relationship to work as expected
  4. I am using JPA2 and JBoss and Hibernate. Do you have any code references to TEST a one-to-many relationship? Any references for a complete project or reading material would help.

Thanks for looking.


原文:https://stackoverflow.com/questions/15374334
更新时间:2022-10-14 16:10

最满意答案

创建列表后添加一秒钟的睡眠。 页面不存在,因为列表尚未完成创建。

# create list and return list id
list_id = twitter.create_list(name=user)['id']

print list_id

time.sleep(1) # Sleep one second

# get users following ids
following_ids = twitter.get_friends_ids(screen_name=user)['ids']

print following_ids

for i in chunks(following_ids, 100):
    # add memebers to list - 100 at a time
    twitter.create_list_members(list_id=list_id, user_id=i)

Add a sleep of one second after creating the list. The page doesn't exist because the list hasn't finished being created.

# create list and return list id
list_id = twitter.create_list(name=user)['id']

print list_id

time.sleep(1) # Sleep one second

# get users following ids
following_ids = twitter.get_friends_ids(screen_name=user)['ids']

print following_ids

for i in chunks(following_ids, 100):
    # add memebers to list - 100 at a time
    twitter.create_list_members(list_id=list_id, user_id=i)

相关问答

更多
  • 好吧,没关系,我想通了。 对于我的路线登记,我想我应该指定该区域作为路线的一部分; 这显然是不正确的。 一旦我删除了路线登记的area段,所有都正常工作。 OK, never mind, I figured it out. for my route registration, I thought I should specify the area as part of the route; this was apparently incorrect. Once I removed the area segm ...
  • 使用HttpStatusCode Enumeration ,特别是HttpStatusCode.NotFound 就像是: HttpWebResponse errorResponse = we.Response as HttpWebResponse; if (errorResponse.StatusCode == HttpStatusCode.NotFound) { // } 哪里 we是一个WebException 。 Use the HttpStatusCode Enumeration, spec ...
  • 创建列表后添加一秒钟的睡眠。 页面不存在,因为列表尚未完成创建。 # create list and return list id list_id = twitter.create_list(name=user)['id'] print list_id time.sleep(1) # Sleep one second # get users following ids following_ids = twitter.get_friends_ids(screen_name=user)['ids'] p ...
  • 您需要允许访问favicon的所有内容。 :) You need to allow access to all for the favicon. :)
  • 对不起,这是我犯的一个非常愚蠢的错误,我从来没有注意到。 在更改项目时,我必须更新包中的条目 jersey.config.server.provider.packages com.javatpoint.rest 到我的新服务类的包。 com.javatpoint.rest是旧项目的包,我改为新项目。 改变它使它工作。 写这里,以 ...
  • 您将控制器定义为@RestController ,它在访问secure/list页面时会导致错误。 我的建议是使用@Controller注释而不是@RestController创建另一个控制器。 @Controller public class SecureListController { @RequestMapping(value={"/secure/list"}, method=RequestMethod.GET) public ModelAndView getSecureList() ...
  • 发生此错误是因为您忘记添加 @RequestMapping(value = "/{name}", method = RequestMethod.GET) 在找到方法之前: @RestController @RequestMapping("/test") public class AreaController { @RequestMapping(value = "/{name}", method = RequestMethod.GET) public RestResponse find(@P ...
  • 尝试 result.resource_server_base_uri = unescape(query_string.resource_server_base_uri); 我相信/它实际上是一个分隔符,但是%2f变成了一个普通的角色,只代表你的网址中的/字符。 unescape()已被弃用; 尝试decodeURIComponent() Try result.resource_server_base_uri = unescape(query_string.resource_server_base_uri) ...
  • 您需要使用screen_name参数调用show_user方法 t = Twython(app_key=settings.TWITTER_CONSUMER_KEY, app_secret=settings.TWITTER_CONSUMER_SECRET, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) print t.show_user(screen_na ...
  • 如果找不到模型, firstOrFail()将抛出错误。 如果你想抓住它,我建议你在global.php中做 哟不需要返回abort() ,如文档中所示 firstOrFail() will throw an error if a model is not found. If you want to catch it I would suggest doing it in the global.php Yo do not need to return the abort() as shown in the ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)