简体   繁体   English

带有SQL Server的Java持久性-无法插入行,但与mysql兼容,为什么? 投诉该表已存在

[英]Java persistence with sql server - cannot insert a row but it works well with mysql, why? Complains that table already exists

Here is my code: 这是我的代码:

package sqlserver;

import it.bsec.target.entity.Colore;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Test1 {

    public static void main(String[] args) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e1) {
            System.out.println("Failed to register the driver.");
        }

        String connectionUrl = "jdbc:sqlserver://localhost:3306;" +
                   "databaseName=target;integratedSecurity=true;encrypt=true;trustServerCertificate=true;";
        try {
            Connection con = DriverManager.getConnection(connectionUrl);
            Statement stmt = con.createStatement();
            String s = "use target";
            String sql = "SELECT * FROM dbo.Colori";
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()) {
                int id  = rs.getInt("Id");
                String desc = rs.getString("Descrizione");
                System.out.println(id + " : " + desc);
            }

            System.setProperty("eclipselink.target-database", "SqlServer");
            System.setProperty("javax.persistence.jdbc.driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.setProperty("javax.persistence.jdbc.url", System.getProperty("jdbc.url", "jdbc:sqlserver://localhost:3306;databaseName=target;integratedSecurity=true;encrypt=true;trustServerCertificate=true;"));
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("TARGET", System.getProperties());
            EntityManager entityManager = factory.createEntityManager();

            Colore c = new Colore();
            c.setId(6);
            c.setDescrizione("WHITE");
            entityManager.persist(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

This query results in insertion of a new row into a table Colori in MySQL. 此查询导致在MySQL中将新行插入到表Colori中。 When I run this example from within Eclipse with SQL Server, this is what I get (and insertion fails): 当我从带有SQL Server的Eclipse中运行此示例时,这是我得到的(插入失败):

1 : BLUE
2 : GREY
3 : GREEN
4 : RED
5 : YELLOW
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: There is already an object named 'Colori' in the database.
Error Code: 2714
Call: CREATE TABLE dbo.Colori (Id INTEGER NOT NULL, Descrizione VARCHAR(255) NULL, PRIMARY KEY (Id))
Query: DataModifyQuery(sql="CREATE TABLE dbo.Colori (Id INTEGER NOT NULL, Descrizione VARCHAR(255) NULL, PRIMARY KEY (Id))")

But it is enough to modify this code slightly like so: 但是只要像这样修改该代码就足够了:

package sqlserver;

import it.bsec.target.entity.Colore;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Test1 {

    public static void main(String[] args) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e1) {
            System.out.println("Failed to register the driver.");
        }

        String connectionUrl = "jdbc:sqlserver://localhost:3306;" +
                   "databaseName=target;integratedSecurity=true;encrypt=true;trustServerCertificate=true;";
        try {
            Connection con = DriverManager.getConnection(connectionUrl);
            Statement stmt = con.createStatement();
            String s = "use target";
            String sql = "SELECT * FROM dbo.Colori";
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()) {
                int id  = rs.getInt("Id");
                String desc = rs.getString("Descrizione");
                System.out.println(id + " : " + desc);
            }

            System.setProperty("eclipselink.target-database", "SqlServer");
            System.setProperty("javax.persistence.jdbc.driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.setProperty("javax.persistence.jdbc.url", System.getProperty("jdbc.url", "jdbc:sqlserver://localhost:3306;databaseName=target;integratedSecurity=true;encrypt=true;trustServerCertificate=true;"));
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("TARGET", System.getProperties());
            EntityManager entityManager = factory.createEntityManager();
            entityManager.getTransaction().begin();
            entityManager.createNativeQuery("insert into dbo.Colori(Id, Descrizione) values ('6', 'WHITE')").executeUpdate();
            entityManager.getTransaction().commit();
            entityManager.persist(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

And this is an error I still get: 这是我仍然得到的错误:

1 : BLUE
2 : GREY
3 : GREEN
4 : RED
5 : YELLOW
[EL Warning]: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: There is already an object named 'Colori' in the database.
Error Code: 2714
Call: CREATE TABLE dbo.Colori (Id INTEGER NOT NULL, Descrizione VARCHAR(255) NULL, PRIMARY KEY (Id))
Query: DataModifyQuery(sql="CREATE TABLE dbo.Colori (Id INTEGER NOT NULL, Descrizione VARCHAR(255) NULL, PRIMARY KEY (Id))")

HOWEVER, THIS TIME INSERTION SUCCEEDS (despite an error)! 但是,此时间插入成功(尽管有错误)! Does anyone understand why is it so and what am I doing wrong? 有谁知道为什么会这样,我在做什么错? In particular, why do I get error saying basically that table exists?? 尤其是为什么我为什么会错误地指出该表存在? Of course it exists, it supposed to, no? 当然它应该存在,不是吗? How else could I try to insert anything into non existent table? 我还能怎么尝试将任何东西插入不存在的表中? How this can be an error? 这怎么可能是一个错误?

I am using slqjdbc4 driver, eclipse link, java 6 EE persistence framework and below, I include code of my Entity Bean: 我正在使用slqjdbc4驱动程序,eclipse链接,java 6 EE持久性框架及以下版本,我包含了Entity Bean的代码:

package it.bsec.target.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="dbo.Colori")
@SuppressWarnings("serial")
public class Colore implements Serializable {

    @Id
    @Column(name = "Id")
    private Integer id;

    @Column(name = "Descrizione", length = 255)
    private String descrizione;

    public Integer getId() {
        return id;
    }

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

    public String getDescrizione() {
        return descrizione;
    }

    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }

}

Is just SQLServer not compatible with java persistence framework? 仅仅是SQLServer与Java持久性框架不兼容吗? I know it sounds strange, but what else can be the reason? 我知道这听起来很奇怪,但是还有什么原因呢? Sorry, but I clearly don't know what is going wrong. 抱歉,但我显然不知道出了什么问题。 Needless to say, the above query works perfectly when executed from within SQL Server Management Studio. 不用说,上述查询在SQL Server Management Studio中执行时效果很好。


EDIT: As suggested by Jens, I have added property eclipselink.ddl-generation and set its value to update, easy fix - now it does work with native queries, however when try an example with where I am trying persist an Entity Bean, it still fails (No error this time!) but it doesn't add any new row into the table. 编辑:正如詹斯建议的那样,我添加了属性eclipselink.ddl-generation并将其值设置为update,很容易修复-现在它确实适用于本机查询,但是当我尝试持久化Entity Bean的示例时仍然失败(这次没有错误!),但是它没有在表中添加任何新行。 Any one knows what am I still missing and where would be a good source of information for this type of things, that I could learn from? 任何人都知道我仍然缺少什么,我可以从中学习到哪些此类信息的良好信息来源? Thanks. 谢谢。

It will be done by JPA. 这将由JPA完成。 try to add the property eclipselink.ddl-generation and set the value to update 尝试添加属性eclipselink.ddl-generation并将其值设置为update

      System.setProperty("eclipselink.ddl-generation", "update");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM