【问题标题】:How can a javax.persistence.Column be defined as an Unsigned TINYINT?如何将 javax.persistence.Column 定义为 Unsigned TINYINT?
【发布时间】:2014-10-13 13:24:55
【问题描述】:

我正在基于 MySQL 数据库中的现有表创建 Java Persistence Entity Bean(使用 NetBeans IDE 8.0.1)。我在此表中遇到了一个类型为 “Unsigned TINYINT(3)” 的字段。我发现可以对define the type of a column as an unsigned int进行以下操作:

private long foo;

@Column(columnDefinition = "UNSIGNED INT(11)")
public long getFoo()
{
    return foo;
}

重现问题的步骤:

我正在尝试按如下方式创建一个字段:

@Size(max = 3)
@Column(name = "WorkingHours", columnDefinition="UNSIGNED TINYINT(3) default '40'")
private Integer workingHours;

问题:

将项目部署到服务器时收到以下错误:

{"JBAS014671: Failed services" => {"jboss.persistenceunit.\"my-project.ear/my-project-ejb.jar#old-db\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"my-project.ear/my-project-ejb.jar#old-db\": javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [create table ... etc.]
    Caused by: javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [create table ... etc.]
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNSIGNED TINYINT(3), ... etc.' at line 1"}}

如果我从我的columnDefinition 中删除 "UNSIGNED"(因此该行变为columnDefinition="TINYINT(3) default '40'"),我的项目部署就成功了。所以似乎 "UNSIGNED" 无法识别。

所以我的问题是:如何将我的列(字段)定义为无符号的 TINYINT?

更多细节:

我不确定它是否重要,但我的 persistence.xml 文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="old-db" transaction-type="JTA">
    <jta-data-source>java:/jboss/datasources/mySQL_pool_old</jta-data-source>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
    </properties>
  </persistence-unit>
</persistence>

【问题讨论】:

  • 您可以将其定义为 WHATEVER THE RDBMS SUPPORTS,因为该语句只是提供给 RDBMS。所以 MySQL 大概不允许 UNSIGNED
  • @NeilStockton 但the MySQL documentationTINYINT 可以是 UNSIGNED..(另请参阅以下 SO 问题:“mysql Tinyint as unsigned” )
  • 为什么不直接查看调用的 SQL/DDL(由您的 JPA 实现)并在 MySQL 控制台中尝试完全相同的操作?这会告诉你它是否存在。
  • @NeilStockton 感谢您的建议,这是一个很好的建议。但是,我刚刚找到了问题的答案。毕竟解决起来并不难。 :)

标签: java mysql jpa unsigned tinyint


【解决方案1】:

在尝试了更多之后,我找到了答案。

"UNSIGNED" 这个词应该在 "TINYINT" 之后而不是之前。该字段应定义如下:

@Size(max = 3)
@Column(name = "WorkingHours", columnDefinition="TINYINT(3) UNSIGNED default '40'")
private Integer workingHours;

我不知道为什么会这样,我只是通过反复试验才发现的。也许其他人可以提供参考说明为什么会这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2016-04-19
    相关资源
    最近更新 更多