首页 \ 问答 \ Hibernate日志记录(Hibernate logging)

Hibernate日志记录(Hibernate logging)

我的应用程序使用Hibernate和Ehcache。

我已使用此log4j.properties配置了log4j:

# Configure the console as our one appender
log4j.rootLogger = INFO, A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n

log4j.logger.org.hibernate=info
### log HQL query parser activity
log4j.logger.org.hibernate.hql.ast.AST=info
### log just the SQL
log4j.logger.org.hibernate.SQL=info
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=info
### log HQL parse trees
log4j.logger.org.hibernate.hql=info
### log cache activity ###
log4j.logger.org.hibernate.cache=info
### log transaction activity
log4j.logger.org.hibernate.transaction=info
### log JDBC resource acquisition
log4j.logger.org.hibernate.jdbc=info
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=info

但在控制台输出中我有很多这样的日志行:

22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_time -> org.hibernate.type.AdaptedImmutableType@1bdedf8
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_timestamp -> org.hibernate.type.AdaptedImmutableType@5264dc
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_dbtimestamp -> org.hibernate.type.AdaptedImmutableType@15bd8eb
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_calendar -> org.hibernate.type.AdaptedImmutableType@fe4dd2
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_calendar_date -> org.hibernate.type.AdaptedImmutableType@1a751ff
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_binary -> org.hibernate.type.AdaptedImmutableType@1f86f75
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_serializable -> org.hibernate.type.AdaptedImmutableType@15daaef
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration materialized_blob -> org.hibernate.type.MaterializedBlobType@9d5241
22:42:06.604 [Thread-15] DEBUG n.s.e.config.ConfigurationFactory - Configuring ehcache from InputStream
22:42:06.606 [Thread-15] DEBUG net.sf.ehcache.config.BeanHandler - Ignoring ehcache attribute xmlns:xsi

是否可以禁用此DEBUG消息? 我找不到任何有效的解决方案。 提前致谢!

PS。 pom.xml仅包含:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.1</version>
</dependency>

My application uses Hibernate with Ehcache.

I have configured log4j with this log4j.properties:

# Configure the console as our one appender
log4j.rootLogger = INFO, A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n

log4j.logger.org.hibernate=info
### log HQL query parser activity
log4j.logger.org.hibernate.hql.ast.AST=info
### log just the SQL
log4j.logger.org.hibernate.SQL=info
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=info
### log HQL parse trees
log4j.logger.org.hibernate.hql=info
### log cache activity ###
log4j.logger.org.hibernate.cache=info
### log transaction activity
log4j.logger.org.hibernate.transaction=info
### log JDBC resource acquisition
log4j.logger.org.hibernate.jdbc=info
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=info

But in console output i have very much log lines like this:

22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_time -> org.hibernate.type.AdaptedImmutableType@1bdedf8
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_timestamp -> org.hibernate.type.AdaptedImmutableType@5264dc
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_dbtimestamp -> org.hibernate.type.AdaptedImmutableType@15bd8eb
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_calendar -> org.hibernate.type.AdaptedImmutableType@fe4dd2
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_calendar_date -> org.hibernate.type.AdaptedImmutableType@1a751ff
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_binary -> org.hibernate.type.AdaptedImmutableType@1f86f75
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration imm_serializable -> org.hibernate.type.AdaptedImmutableType@15daaef
22:42:06.603 [Thread-15] DEBUG org.hibernate.type.BasicTypeRegistry - Adding type registration materialized_blob -> org.hibernate.type.MaterializedBlobType@9d5241
22:42:06.604 [Thread-15] DEBUG n.s.e.config.ConfigurationFactory - Configuring ehcache from InputStream
22:42:06.606 [Thread-15] DEBUG net.sf.ehcache.config.BeanHandler - Ignoring ehcache attribute xmlns:xsi

Is it possible to disable this DEBUG messages? I can not find any working solution. Thanks in advance!

PS. pom.xml contains only:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.1</version>
</dependency>

原文:https://stackoverflow.com/questions/7246794
更新时间:2022-10-10 15:10

最满意答案

即使我在没有键和关系的情况下在另一个数据库中创建表,我也无法重现这个问题。 所以我确定您的模型存在问题。 不幸的是你没有添加我可以比较的代码,所以我不知道有什么不同并直接回答问题。 我唯一能做的就是展示对我有用的东西。 但是,首先我有一些评论。


我想你不应该听完这篇文章。 因为没有理由将上下文添加到现有数据库。

就像Ivan Stoev提到的那样,你不应该混淆上下文。 Identity上下文用于验证用户身份。 它存储凭据,用户角色和声明。 声明旨在添加有关用户的身份信息。

实际上,可以删除ApplicationUser模板的默认Hometown字段,因为它是一个标识声明,应存储在AspNetUserClaims表中。 不需要扩展ApplicationUser。 实际上我想不出任何扩展ApplicationUser的理由。

关于这些角色,这些并不是真正的主张,因为它们对身份没有任何说明,而是用于授权。 这就是它们存储在AspNetUserRoles表中的原因。 不幸的是,角色作为角色声明被添加到身份中,这使得事情变得混乱。

请注意,身份信息存在于声明中。 这意味着应用程序不必调用Identity上下文。 例如,User.IsInRole检查当前标识的角色声明,而不是表中存储的角色。

关于不同的上下文,其他上下文(我通常称之为业务模型)与Identity上下文没有任何共同之处。 电子邮件和其他字段不是商业模式的一部分,也没有意义。 您可能认为这些字段是多余的,但实际上它们不是。 我可以使用谷歌帐户登录,但对于企业使用我的工作电子邮件地址。

保持上下文分离有几个原因。

  • 分离关注点。 假设您希望将来与另一个认证框架进行交换。 如果您希望支持单点登录(SSO),请执行IdentityServer。
  • 如果另一个应用程序需要相同的登录,则无法将users表移动到另一个数据库。 因此,您最终还会将其他上下文添加到数据库中。
  • 迁移问题。 如果混合上下文,则迁移将失败。
  • 它会让事情变得更加容易。 这是你遇到的第一个问题,而不是最后一个问题。

正如文章中提到的:

此时,如果您需要将自己的表中的任何关系(例如外键)添加到这些表中,欢迎您这样做,但不要直接或稍后在任何POCO类上修改任何Entity Framework 2.0表。 这样做会根据我收到的反馈导致错误。

那么如果您不应该从应用程序访问身份上下文,如何管理信息?

对于当前用户,您无需访问users表。 所有信息都出现在身份声明中。 访问身份上下文的唯一原因是允许用户登录。 除了用户管理。

您可以通过添加对用户(userid)的引用来满足要求。 如果需要在报表中显示其他用户的信息(如名称),请在业务上下文中创建用户表以存储信息。 您可以向此表添加关系,因为它是同一上下文的一部分。

如果您对此方法有疑问,请与我们联系。


现在代码对我有用。 像其他人提到的那样,添加线路的可能性不大:

public ICollection<Employee> Employees { get; set; }

是原因。 如果没有virtual关键字,我认为它甚至被忽略(保持为null)。

当我按照文章的步骤进行操作时,我最终会得到以下模型:

public class ApplicationUser : IdentityUser
{
    public string Hometown { get; set; }

    //public virtual ICollection<Employee> Employees { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        // Disable migrations
        //Database.SetInitializer<ApplicationDbContext>(null);
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

然后我添加Employee类并取消注释上面的ApplicationUser类中的行:

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }

    //public virtual ApplicationUser ApplicationUser { get; set; }

    public string ApplicationUserId { get; set; }
}

在数据库中我添加了表:

CREATE TABLE [dbo].[Employees](
    [Id] [int] NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [ApplicationUserId] [nvarchar](128) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

您可以使用[ForeignKey]属性来使用其他字段名称。

您可以尝试这样做或选择将两个上下文分开。


I cannot reproduce the issue, even when I create the tables in another database without keys and relations. So I'm sure that there is a problem with your model. Unfortunately you didn't add code which I can compare, so I can't tell what is different and answer the question directly. The only thing I can do is to show what works for me. However, first I have some remarks.


I think you shouldn't follow the article. As there is no reason to add the context to an existing database.

Like Ivan Stoev mentioned you are not supposed to mix contexts. The Identity context is meant to authenticate the user. It stores the credentials, the roles of the user and claims. Where claims are meant to add identity information about the user.

In fact, the default Hometown field of the ApplicationUser template can be removed, as it is an identity claim which should be stored in the AspNetUserClaims table. Not something you need to extend the ApplicationUser for. Actually I can't think of any reason to extend the ApplicationUser.

About the roles, these are not really claims, as they tell nothing about the identity but rather are used for authorization. That's why it's fine that they are stored in the AspNetUserRoles table. Unfortunately roles are added to the identity as role claims, which makes things confusing.

Please note that the Identity information is present in the claims. This means that the application doesn't have to call the Identity context. E.g. User.IsInRole checks the role claims of the current identity, not the roles stored in the table.

About the different contexts, the other context (which I usually call the business model) has nothing in common with the Identity context. Email and other fields are not part, nor have meaning to the business model. You may think that those fields are redundant, but in fact they are not. I could login using a google account, but for the business use my work email address.

There are several reasons to keep the context seperated.

  • Seperation of concerns. Suppose you want to exchange the authentication framework in the future with another one. Like implement IdentityServer in case you want to support single sign-on (SSO).
  • You can't move the users table to another database if another application needs the same logins. So you'll end up adding other contexts as well to the database.
  • Trouble with migrations. If you mix the contexts then migrations will fail.
  • It'll makes things far more easier. This is the first problem you've encountered, not the last.

As also mentioned in the article:

At this point if you need to add any relationships (E.g. foreign keys) from your own tables to these tables you are welcome to do so but do not modify any of the Entity Framework 2.0 tables directly or later on any of their POCO classes. Doing so will result in errors based upon feedback I’ve received.

So how to manage the information if you shouldn't access the identity context from your application?

For the current user you don't need to access the users table. All the information is present in the identity claims. The only reason to access the identity context is to allow a user to login. Besides user management.

You can suffice by adding a reference to the user (the userid). If you need to show information of other users (like name) in a report, then create a user table in your business context to store the information. You can add relations to this table, as it is part of the same context.

Please let me know if you have questions about this approach.


Now the code that works for me. Like others have mentioned, it is not likely that adding the line:

public ICollection<Employee> Employees { get; set; }

is the cause. Without the virtual keyword I think it is even ignored (remains null).

When I follow the steps of the article then I end up with the following model:

public class ApplicationUser : IdentityUser
{
    public string Hometown { get; set; }

    //public virtual ICollection<Employee> Employees { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        // Disable migrations
        //Database.SetInitializer<ApplicationDbContext>(null);
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

And then I add the Employee class and uncomment the line in the ApplicationUser class above:

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }

    //public virtual ApplicationUser ApplicationUser { get; set; }

    public string ApplicationUserId { get; set; }
}

In the database I added the table:

CREATE TABLE [dbo].[Employees](
    [Id] [int] NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [ApplicationUserId] [nvarchar](128) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

You can use the [ForeignKey] attribute to use a different field name.

You can try this or choose to keep both contexts seperated instead.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。